├── .github ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── LICENSE ├── Lifecycle-patterns ├── Anti-patterns │ └── README.md ├── README.md ├── README_ja.md ├── README_ko.md ├── Train-then-serve-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png └── Training-to-serving-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── Operation-patterns ├── Anti-patterns │ ├── No-logging-pattern │ │ ├── design_en.md │ │ ├── design_ja.md │ │ ├── design_ko.md │ │ └── diagram.png │ ├── Nobody-knows-pattern │ │ ├── design_en.md │ │ ├── design_ja.md │ │ ├── design_ko.md │ │ └── diagram.png │ ├── README.md │ ├── README_ja.md │ └── README_ko.md ├── Condition-based-serving-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── Data-model-versioning-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ ├── diagram0.png │ └── diagram1.png ├── Model-in-image-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── Model-load-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── Parameter-based-serving-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── Prediction-log-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── Prediction-monitoring-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── README.md ├── README_ja.md └── README_ko.md ├── QA-patterns ├── Anti-patterns │ ├── Offline-only-pattern │ │ ├── design_en.md │ │ ├── design_ja.md │ │ ├── design_ko.md │ │ └── diagram.png │ ├── README.md │ ├── README_ja.md │ └── README_ko.md ├── Loading-test-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── Online-ab-test-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── README.md ├── README_ja.md ├── README_ko.md └── Shadow-ab-test-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── README.md ├── README_ja.md ├── README_ko.md ├── Serving-patterns ├── Anti-patterns │ ├── All-in-one-pattern │ │ ├── design_en.md │ │ ├── design_ja.md │ │ ├── design_ko.md │ │ └── diagram.png │ ├── Online-bigsize-pattern │ │ ├── design_en.md │ │ ├── design_ja.md │ │ ├── design_ko.md │ │ └── diagram.png │ ├── README.md │ ├── README_ja.md │ └── README_ko.md ├── Asynchronous-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ ├── diagram1.png │ └── diagram2.png ├── Batch-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── Data-cache-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ ├── diagram1.png │ └── diagram2.png ├── Microservice-horizontal-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ ├── diagram1.png │ ├── diagram2.png │ └── diagram3.png ├── Microservice-vertical-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ ├── diagram1.png │ └── diagram2.png ├── Multiple-stage-prediction-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── Prediction-cache-pattern │ ├── CONTRIBUTING.md │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── Prediction-circuit-break-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── Prep-pred-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ ├── diagram1.png │ └── diagram2.png ├── README.md ├── README_ja.md ├── README_ko.md ├── Serving-template-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── Synchronous-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png └── Web-single-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── Training-patterns ├── Anti-patterns │ ├── Only-me-pattern │ │ ├── design_en.md │ │ ├── design_ja.md │ │ ├── design_ko.md │ │ └── diagram.png │ ├── README.md │ ├── README_ja.md │ ├── README_ko.md │ ├── Too-many-pipes-pattern │ │ ├── design_en.md │ │ ├── design_ja.md │ │ ├── design_ko.md │ │ └── diagram.png │ └── Training-code-in-serving-pattern │ │ ├── design_en.md │ │ ├── design_ja.md │ │ ├── design_ko.md │ │ └── diagram.png ├── Batch-training-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── Parameter-and-architecture-search-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── Pipeline-training-pattern │ ├── design_en.md │ ├── design_ja.md │ ├── design_ko.md │ └── diagram.png ├── README.md ├── README_ja.md └── README_ko.md ├── _config.yml ├── template_antipattern.md └── template_design.md /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### What is your issue? 2 | 3 | ### Why is it issue? 4 | 5 | ### How do you expect to be? -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Please read the CLA carefully before submitting your contribution to Mercari. 2 | Under any circumstances, by submitting your contribution, you are deemed to accept and agree to be bound by the terms and conditions of the CLA. 3 | 4 | https://www.mercari.com/cla/ -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | .DS_Store 107 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Mercari, Inc. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Lifecycle-patterns/Anti-patterns/README.md: -------------------------------------------------------------------------------- 1 | # Lifecycle Antipatterns -------------------------------------------------------------------------------- /Lifecycle-patterns/README.md: -------------------------------------------------------------------------------- 1 | # Lifecycle patterns 2 | 3 | - [Train-then-serve pattern](./Train-then-serve-pattern/design_en.md) 4 | 5 | - [Training-to-serving pattern](./Training-to-serving-pattern/design_en.md) -------------------------------------------------------------------------------- /Lifecycle-patterns/README_ja.md: -------------------------------------------------------------------------------- 1 | # Lifecycle patterns 2 | 3 | - [Train-then-serve pattern](./Train-then-serve-pattern/design_ja.md) 4 | 5 | - [Training-to-serving pattern](./Training-to-serving-pattern/design_ja.md) -------------------------------------------------------------------------------- /Lifecycle-patterns/README_ko.md: -------------------------------------------------------------------------------- 1 | # Lifecycle patterns 2 | 3 | - [Train-then-serve pattern](./Train-then-serve-pattern/design_ko.md) 4 | 5 | - [Training-to-serving pattern](./Training-to-serving-pattern/design_ko.md) -------------------------------------------------------------------------------- /Lifecycle-patterns/Train-then-serve-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Train-then-serve pattern 2 | 3 | ## Usecase 4 | - To design end-to-end workflow of machine learning model into production. 5 | - When you want to separate training and release into different workflows. 6 | - To manually evaluate model for release quality. 7 | - To evaluate models in production. 8 | 9 | ## Architecture 10 | When you want to design an architecture and workflow to connect training and serving, you will be combining the training patterns and serving patterns. You can use this train-then-serve pattern, a mixture of multiple patterns, to manually release a trained model after evaluation. Since the workflow includes human tasks, it is not suitable for requirement with frequent model release, but it assures quality of the model and system.
11 | It is possible to use the [model load pattern](../../Operation-patterns/Model-load-pattern/design_en.md) or the [model-in-image pattern](../../Operation-patterns/Model-in-image-pattern/design_en.md) to connect between the training and serving. Criteria of selecting which one depends on how you like to manage model and prediction server. If you want to update the model without change in the current server, you may choose the [model load pattern](../../Operation-patterns/Model-load-pattern/design_en.md), while you need to update the whole server for the [model-in-image pattern](../../Operation-patterns/Model-in-image-pattern/design_en.md).
12 | It is effective to use the [parameter-based serving pattern](../../Operation-patterns/Parameter-based-serving-pattern/design_en.md) for the production serving. It will enable you to update the behaviour of the prediction with modifying an environmental variable in the proxy. For sake of service management, it is mandatory to use the [prediction log pattern](../../Operation-patterns/Prediction-log-pattern/design_en.md) and the [prediction monitoring pattern](../../Operation-patterns/Prediction-monitoring-pattern/design_en.md).
13 | Selecting a serving pattern and QA pattern depends on the production requirement. It will naturally be a combination of patterns. The diagram shows usage of the [web single pattern](../../Serving-patterns/Web-single-pattern/design_en.md) and the [online AB testing pattern](../../QA-patterns/Online-ab-test-pattern/design_en.md). The log will be recorded into a DWH to be used to improve the model and retraining.
14 | An advantage of separating training and serving phases is to evaluate your model before release. If the evaluation based only on your test dataset is not good enough for release, or if manual quality assuarance is required, then this pattern may fit good. In addition, the pattern separates the training and serving phases to isolate issue in the training pipeline from the release and serving system, that strengthens service availability. On the other hand, it is not suitable for usecase where you need to update the model realtime or frequently. 15 | 16 | 17 | ## Diagram 18 | ![diagram](diagram.png) 19 | 20 | 21 | ## Pros 22 | - Manual model evaluation before release. 23 | - Isolate workflow and failure in each phase. 24 | 25 | ## Cons 26 | - Not automated. 27 | 28 | ## Needs consideration 29 | - Combination of training, QA, operation and serving patterns. 30 | - Release standard. 31 | - Release frequency. -------------------------------------------------------------------------------- /Lifecycle-patterns/Train-then-serve-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Train-then-serve pattern 2 | 3 | ## Usecase 4 | - 機械学習モデルを本番環境で使うためのワークフローをデザインしたいとき 5 | - 学習とリリースを別のワークフローで実行したいとき 6 | - 学習後にモデルを人手で評価し、リリース判定をしたいとき 7 | - 学習したモデルを本番サービスにリリースし、評価したいとき 8 | 9 | ## Architecture 10 | 学習パイプラインと推論器のリリースを分かれたワークフローで実施したい場合、学習パターンとサービング・パターンを組み合わせた構成を取ることが可能です。本パターンでは学習後に人手でモデルや推論器のスピード等を評価し、リリース判定を実施することができます。ワークフローに人間による評価が入るため、頻繁にモデルをリリースするには向かない仕組みですが、確実なモデル評価を行うことが可能になります。
11 | 学習と推論の間をつなぐ方法は[モデル・ロード・パターン](../../Operation-patterns/Model-load-pattern/design_ja.md)や[モデル・イン・イメージ・パターン](../../Operation-patterns/Model-in-image-pattern/design_ja.md)を利用することが可能です。いずれを選択するかはモデルと推論器の管理方針次第です。[モデル・ロード・パターン](../../Operation-patterns/Model-load-pattern/design_ja.md)であれば学習したモデルを既存の推論器の更新でリリース可能でしょうし、[モデル・イン・イメージ・パターン](../../Operation-patterns/Model-in-image-pattern/design_ja.md)であれば推論器自体の更新が必要になります。
12 | モデルを本番サービスに組み込む方法は[パラメータ・ベース・サービング・パターン](../../Operation-patterns/Parameter-based-serving-pattern/design_ja.md)が有効です。プロキシの環境変数にリリースしたモデルの推論器を登録することで、推論リクエスト先に追加することが可能です。サービス運営の観点で、[推論ログパターン](../../Operation-patterns/Prediction-log-pattern/design_ja.md)および[推論監視パターン](../../Operation-patterns/Prediction-monitoring-pattern/design_ja.md)は必須でしょう。
13 | サービング・パターンやQAパターンの選択は本番サービスの仕様次第ですが、実運用では複数のパターンの組み合わせになることが多いと思います。下図では[Webシングル・パターン](../../Serving-patterns/Web-single-pattern/design_ja.md)と[オンラインABテスト・パターン](../../QA-patterns/Online-ab-test-pattern/design_ja.md)の組み合わせにしています。オンラインABテストのログは[推論ログ・パターン](../../Operation-patterns/Prediction-log-pattern/design_ja.md)でDWHに登録し、再学習やモデル改善のためのデータセットにしていく構成になります。
14 | 学習と推論モデルのリリースを分離する利点はリリース前にモデルの評価を行う余地がある点です。テストデータセットでの評価では受け入れテストとして不足するようなワークロードの場合、この構成を取ることができます。加えて、学習パイプラインの障害が推論モデルのリリースに直接的な影響を及ぼさないため、サービスとしての耐障害性も担保されます。逆に難点は、学習後に自動的に推論器がリリースされないため、モデルリリースの手間やリアルタイムな更新には不向きになります。 15 | 16 | 17 | ## Diagram 18 | ![diagram](diagram.png) 19 | 20 | 21 | ## Pros 22 | - モデルのリリース前にマニュアルで評価可能。 23 | - 学習パイプラインと推論サービスの障害やリソース、ワークフローを分離可能。 24 | 25 | ## Cons 26 | - モデルのリリースにマニュアル実行が必要。 27 | 28 | ## Needs consideration 29 | - 学習パターン、QAパターン、サービング・パターンの組み合わせ方法。 30 | - モデルのリリース判定基準。 31 | - モデルのリリース頻度。 -------------------------------------------------------------------------------- /Lifecycle-patterns/Train-then-serve-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Train-then-serve pattern 2 | 3 | ## Usecase 4 | - 머신러닝 모델부터 실제 운영까지 전체 워크플로우를 디자인하는 경우. 5 | - 학습과 릴리즈를 각각 다른 워크플로우로 분리할 때. 6 | - 모델의 릴리즈 품질을 수동으로 평가할 때. 7 | - 실제 운영 환경에서 모델을 평가할 때. 8 | 9 | ## Architecture 10 | 학습과 서빙을 연결하는 워크플로우를 설계할 때, 학습 패턴과 서빙 패턴을 조합하는 구성을 할 수 있습니다. 평가가 끝난 학습된 모델을 수동으로 릴리즈를 할 때, 여러 패턴을 조합한 train-then-serve 패턴을 사용할 수 있습니다. 이 워크플로우에서는 사람에 의한 평가가 들어가기 때문에, 자주 모델 릴리즈를 하려면 적합하지 않은 구조이지만, 모델과 시스템의 품질을 확실히 보장할 수 있습니다. 11 |
12 | 학습과 서빙을 연결하기 위해 [model load pattern](../../Operation-patterns/Model-load-pattern/design_ko.md)이나 [model-in-image pattern](../../Operation-patterns/Model-in-image-pattern/design_ko.md)을 사용할 수 있습니다. 이는 모델과 예측 서버 관리하는 방법에 따라 결정할 수 있습니다. 현재 서버에서 변경 없이 모델을 업데이트하려면 [model load pattern](../../Operation-patterns/Model-load-pattern/design_ko.md)을, 전체 서버를 업데이트해야 한다면 [model-in-image pattern](../../Operation-patterns/Model-in-image-pattern/design_ko.md)을 선택할 수 있습니다. 13 |
14 | 실제 운영 환경에서는 프록시 환경 변수 수정으로 운영 중인 모델의 예측 동작을 업데이트 할 수 있는 [parameter-based serving pattern](../../Operation-patterns/Parameter-based-serving-pattern/design_ko.md)이 효과적일 수도 있습니다. 서비스 관리 측면에서 [prediction log pattern](../../Operation-patterns/Prediction-log-pattern/design_ko.md)과 [prediction monitoring pattern](../../Operation-patterns/Prediction-monitoring-pattern/design_ko.md)은 반드시 사용되어야 합니다. 15 |
16 | 서빙 패턴과 QA 패턴을 선택하는 것은 운영 요건에 따라 달라질 수 있지만, 결국 여러 패턴의 조합이 될 것이라 생각합니다. 아래 그림은 [web single pattern](../../Serving-patterns/Web-single-pattern/design_ko.md)과 [online AB testing pattern](../../QA-patterns/Online-ab-test-pattern/design_ko.md)의 조합을 표현한 다이어그램입니다. 로그들은 데이터 웨어하우스에 기록되어 모델 개선과 재학습에 사용됩니다. 17 |
18 | 학습과 서빙 단계 분리의 장점은 릴리즈 전에 모델을 평가할 수 있다는 것입니다. 만약 릴리즈 전 테스트 데이터셋 기반의 평가가 충분하지 않다 생각되거나 수동 품질 보증이 필요한 경우 이 구성을 생각해 볼 수 있습니다. 또한, 이 패턴은 학습 및 서빙을 구분함으로써 학습 파이프라인의 장애가 서빙 시스템과 릴리즈에 직접적인 영향을 끼치지 않아 서비스 가용성을 강화시켜줍니다. 하지만 모델을 실시간 혹은 자주 업데이트해야 하는 경우는 적합하지 않습니다. 19 | 20 | ## Diagram 21 | ![diagram](diagram.png) 22 | 23 | 24 | ## Pros 25 | - 릴리즈 전 수동으로 모델을 평가합니다. 26 | - 워크플로우와 학습 및 릴리즈 장애를 분리할 수 있습니다. 27 | 28 | ## Cons 29 | - 자동화가 되지 않습니다. 30 | 31 | ## Needs consideration 32 | - 학습 패턴과, QA 패턴, 서빙 패턴 조합 방법. 33 | - 모델 릴리즈 기준. 34 | - 모델 릴리즈 빈도. 35 | -------------------------------------------------------------------------------- /Lifecycle-patterns/Train-then-serve-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Lifecycle-patterns/Train-then-serve-pattern/diagram.png -------------------------------------------------------------------------------- /Lifecycle-patterns/Training-to-serving-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Training-to-serving pattern 2 | 3 | ## Usecase 4 | - To design end-to-end workflow of machine learning model into production. 5 | - To release a model right after training. 6 | - To automatically deploy a model into production. 7 | - When your model training is stable enough. 8 | - When you need to update models frequently. 9 | 10 | ## Architecture 11 | When you want to design an architecture and workflow to connect training and serving, you will be combining the training patterns and serving patterns. If your require to deploy your model continuously with training pipeline, you can use the training-to-serving pattern. The aim of the pattern is to build the model server once the training completes and release automatically. If your usecase requires to udpate model frequently that manual evaluation is inoperative, then the pattern fits good.
12 | For the training pipeline, you may choose the [batch training pattern](../../Training-patterns/Batch-training-pattern/design_en.md) or the [pipeline training pattern](../../Training-patterns/Pipeline-training-pattern/design_en.md). It is a bit risky to select the [parameter and architecture search pattern](../../Training-patterns/Parameter-and-architecture-search-pattern/design_en.md) for its trained model quality may not be stable.
13 | It is possible to use the [model load pattern](../../Operation-patterns/Model-load-pattern/design_en.md) or the [model-in-image pattern](../../Operation-patterns/Model-in-image-pattern/design_en.md) to connect between the training and serving. Criteria of selecting which one depends on how you like to manage model and prediction server. If you want to update the model without change in the current server, you may choose the [model load pattern](../../Operation-patterns/Model-load-pattern/design_en.md), while you need to update the whole server for the [model-in-image pattern](../../Operation-patterns/Model-in-image-pattern/design_en.md).
14 | It may be good to use the [microservice horizontal pattern](../../Serving-patterns/Microservice-horizontal-pattern/design_en.md) for serving. The pattern aims to deploy a new prediction server parallelly to the others, and the proxy discovers the new service to be added to the prediction target.
15 | For sake of service management, it is mandatory to use the [prediction log pattern](../../Operation-patterns/Prediction-log-pattern/design_en.md) and the [prediction monitoring pattern](../../Operation-patterns/Prediction-monitoring-pattern/design_en.md).
16 | It is possible to release a model right after training. Note that it is necessary to have the model training and evaluation be stable that their quality will not get affected easily, and their pipeline be available. If the quality of trained model varies so often, the pattern will be risky. If the pipeline is not stable, then the whole workflow would be unstable. It is also important to consider if all the model should be in production. If a model is not necessary or useless in any reason, say out of date or performance degradation, you need to eliminate the one. It is simple to operate if it is possible to remove a prediction server on time elapsed, though there may be a chance that a model still in use may be removed. On the other hand, it is smarter if it possible to evaluate the production model regularly to outdate one, though the operation may be complex with taking other risk of managing the evaluation. 17 | 18 | ## Diagram 19 | ![diagram](diagram.png) 20 | 21 | 22 | ## Pros 23 | - Release right after training. 24 | - Frequent release. 25 | 26 | ## Cons 27 | - Requires training pipeline, auto release, and service discovery. 28 | - Not suitable for unstable training. 29 | 30 | ## Needs consideration 31 | - Stabilize training, automate pipelines and requires service level on each phase. 32 | - Service discovery and removal policy for serving. -------------------------------------------------------------------------------- /Lifecycle-patterns/Training-to-serving-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Training-to-serving pattern 2 | 3 | ## Usecase 4 | - モデルの学習完了後、自動リリースしたいとき 5 | - リリースしたモデルを自動で本番サービスに組み込みたいとき 6 | - モデルを安定して学習することができるとき 7 | - モデルの更新が頻繁に発生するとき 8 | 9 | ## Architecture 10 | 学習パイプラインと推論器のリリースを同一のワークフローで連続して実行する場合、学習-推論パターンを選択することができます。本パターンでは学習パイプラインを実行し、モデルをビルド、推論器をビルドした後に、自動的に本番サービスにリリースして推論に組み込むことを目的としています。モデルの更新が頻繁に発生し、マニュアルでの評価が不可能な場合、本パターンを選択することが可能です。
11 | 学習パイプラインは[バッチ学習パターン](../../Training-patterns/Batch-training-pattern/design_ja.md)や[パイプライン学習パターン](../../Training-patterns/Pipeline-training-pattern/design_ja.md)を選択することが可能です。[パラメータ&アーキテクチャ探索パターン](../../Training-patterns/Parameter-and-architecture-search-pattern/design_ja.md)はアウトプットが安定するとは限らないため、本パターンと組み合わせるには不向きな場合が多いです。
12 | 学習されたモデルは[モデル・ロード・パターン](../../Serving-patterns/Model-load-pattern/design_ja.md)または[モデル・イン・イメージ・パターン](../../Serving-patterns/Model-in-image-pattern/design_ja.md)でリリースします。推論器のベースとなるサーバ・イメージが共有可能であれば[モデル・ロード・パターン](../../Serving-patterns/Model-load-pattern/design_ja.md)が有効ですが、サーバ・イメージとモデルを1:1対応で管理したい場合は[モデル・イン・イメージ・パターン](../../Serving-patterns/Model-in-image-pattern/design_ja.md)が有効です。
13 | 推論パターンは[並列マイクロサービス・パターン](../../Serving-patterns/Microservice-horizontal-pattern/design_ja.md)が良いでしょう。新しい推論器を他の推論器と並列に自動デプロイしていき、プロキシでサービス・ディスカバリを組み込むことでリリースされた推論器を自動で発見、接続するというワークフローです。
14 | サービス運営の観点で、[推論ログパターン](../../Operation-patterns/Prediction-log-pattern/design_ja.md)および[推論監視パターン](../../Operation-patterns/Prediction-monitoring-pattern/design_ja.md)は必須でしょう。
15 | 学習-推論パターンでは学習後に自動的にモデルをリリースし、本番サービスに組み込むことが可能です。注意点として、モデルの学習と評価結果が大きく上下しないことや、学習パイプラインが安定稼働することが必要になります。モデル学習が不安定な場合、本番サービスに適さないモデルがリリースされるリスクとなります。学習パイプラインが不安定な場合、そもそも学習やリリースが正常動作しないことが懸念点です。また、リリースしたすべてのモデルを常に稼働させ続ける必要があるか、検討が必要です。何らかの理由でモデルが不要になった場合(たとえば学習に使用したデータが古く、推論の精度が下がった場合)、当該推論器を本番サービスから除外する必要があります。可能であれば、一定期間が経過したら自動で推論器を除外する運用であれば、容易に開発することが可能ですが、サービスの目的次第では有用な推論器が削除される懸念があります。他方でモデルの評価等を基準に除外を判定する場合、評価パイプラインを開発し運用する必要がありますが、有用な推論器を削除するリスクを軽減できます。 16 | 17 | ## Diagram 18 | ![diagram](diagram.png) 19 | 20 | 21 | ## Pros 22 | - 学習後のモデルを自動で本番サービスにリリースすることが可能 23 | - 頻繁にモデルをリリースすることが可能 24 | 25 | ## Cons 26 | - 学習パイプライン、自動リリース、サービス・ディスカバリ等を開発する必要がある 27 | - モデルの学習結果が不安定な場合は本パターンは不向き 28 | 29 | ## Needs consideration 30 | - モデル学習の安定性、学習パイプラインと自動リリースの安定性とサービスレベル 31 | - サービス・ディスカバリおよび不要な推論器の削除ポリシー -------------------------------------------------------------------------------- /Lifecycle-patterns/Training-to-serving-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Training-to-serving pattern 2 | 3 | ## Usecase 4 | - 머신러닝 모델부터 실제 운영까지 전체 워크플로우를 디자인하는 경우. 5 | - 학습 직후 모델을 출시할 경우. 6 | - 모델을 실제 운영 환경까지 자동으로 배포할 경우. 7 | - 모델을 안정적으로 학습할 수 있을 경우. 8 | - 모델을 자주 업데이트해야 할 경우. 9 | 10 | ## Architecture 11 | 학습과 서빙을 연결하는 워크플로우를 설계할 때, 학습 패턴과 서빙 패턴을 조합하는 구성을 할 수 있습니다. 학습 파이프라인과 함께 모델을 계속해서 배포해야 하는 경우, 이 패턴을 사용할 수 있습니다. 이 패턴은 학습 파이프라인이 완료되면 자동으로 릴리즈하여 모델 서버를 구축할 수 있습니다. 모델이 자주 업데이트되고 수동 평가가 어려울 경우, 적합한 패턴입니다. 12 |
13 | 학습 파이프라인으로는 [batch training pattern](../../Training-patterns/Batch-training-pattern/design_ko.md)이나 [pipeline training pattern](../../Training-patterns/Pipeline-training-pattern/design_ko.md)을 선택할 수 있습니다. [parameter and architecture search pattern](../../Training-patterns/Parameter-and-architecture-search-pattern/design_ko.md)은 학습 모델의 품질이 안정적이라고 할 수 없기 때문에 이 패턴과 적합하지 않은 경우가 많습니다. 14 |
15 | [model load pattern](../../Operation-patterns/Model-load-pattern/design_ko.md)이나 [model-in-image pattern](../../Operation-patterns/Model-in-image-pattern/design_ko.md)을 사용하여 학습과 서빙을 연결할 수 있는데, 원하는 모델과 예측 서버 관리 방법에 따라 결정할 수 있습니다. 현재 서버에서 변경 없이 모델을 업데이트하려면 [model load pattern](../../Operation-patterns/Model-load-pattern/design_ko.md)을, 모든 서버를 업데이트하려면 [model-in-image pattern](../../Operation-patterns/Model-in-image-pattern/design_ko.md)을 선택할 수 있습니다. 16 |
17 | 서빙할 때는 [microservice horizontal pattern](../../Serving-patterns/Microservice-horizontal-pattern/design_ko.md)을 사용하는 것이 좋습니다. 이 패턴은 새로운 예측 서버를 다른 서버와 병렬로 배치하고, 프록시를 통해 서비스 검색하여 예측 서버들과 연결해 줍니다. 18 |
19 | 서비스 관리 관점에서 [prediction log pattern](../../Operation-patterns/Prediction-log-pattern/design_ko.md)과 [prediction monitoring pattern](../../Operation-patterns/Prediction-monitoring-pattern/design_ko.md) 사용은 필수입니다. 20 |
21 | 이 패턴에서는 학습 후 자동으로 모델을 릴리즈하고 실제 서비스에 투입될 수 있습니다. 22 | 하지만, 반드시 학습과 평가가 안정적이고 학습 파이프라인이 안정적으로 가동되어야 합니다. 학습 모델이 불안정한 경우 오히려 이 패턴은 위험할 수 있습니다. 학습 파이프라인이 불안정한 경우, 전체 워크플로우가 모두 불안정해질 수 있습니다. 또, 실제 운영 환경에 있는 모든 모델을 항상 가동해 둘 필요가 있는지 검토해보아야 합니다. 만약 모델이 필요하지 않은 경우(예를 들어 오래되거나, 성능이 저하된 경우), 해당 모델을 서비스에서 제외시켜야 합니다. 일정 기간이 경과하면 자동으로 예측 서버에서 제외하는 운영 방식이라면 간단하겠지만, 서비스의 목적에 따라 사용되고 있는 모델이 제거될 우려가 있습니다. 대신, 모델을 계속 평가하는 파이프라인을 개발하고 운영한다면 운영은 좀 더 복잡해지겠지만 사용 중인 모델을 제거하는 위험은 줄일 수 있습니다. 23 | 24 | ## Diagram 25 | ![diagram](diagram.png) 26 | 27 | 28 | ## Pros 29 | - 학습 후 바로 서비스에 릴리즈가 가능합니다. 30 | - 릴리즈를 자주 할 수 있습니다. 31 | 32 | ## Cons 33 | - 학습 파이프라인, 자동 릴리즈, 서비스 디스커버리 등을 개발해야 합니다. 34 | - 모델 학습 결과가 불안정할 경우 이 패턴은 부적합합니다. 35 | 36 | 37 | ## Needs consideration 38 | - 모델 학습 안정화, 파이프라인 자동화, 각 단계별 서비스 수준이 요구됩니다. 39 | - 서비스 디스커버리와 불필요한 모델 제거 정책이 필요합니다. 40 | -------------------------------------------------------------------------------- /Lifecycle-patterns/Training-to-serving-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Lifecycle-patterns/Training-to-serving-pattern/diagram.png -------------------------------------------------------------------------------- /Operation-patterns/Anti-patterns/No-logging-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # No logging pattern 2 | 3 | ## Case 4 | - Not taking log or profile. 5 | 6 | ## Situation 7 | Not only for a machine learning system, but system in general, taking log is very important for operation and improvement. Without log in production system, you cannot fetch error, troubleshoot and improve your environment, that makes the system blackbox. Especially for a machine learning system, tracing inference result to related event logging will enable system and model improvement as well as business planning.
8 | An interesting and challenging part of working with machine learning is that machine learning in nature is tightly related to business scheme or user experience. Making a prediction to lead to an action or automation in sophisticated manner is something that traditional if-else statement is difficult to realize, and machine learning can challenge. Note that influencing business or user behavior, or even physical world, requires fit to the actual environment, which needs traceability from the model and system. 9 | 10 | ## Diagram 11 | ![diagram](diagram.png) 12 | 13 | 14 | ## Pros 15 | - You don't have to pay for log storage. 16 | 17 | ## Cons 18 | - You cannot operate and improve your system. 19 | 20 | ## Work around 21 | - At least, get logs of fatal, error, warning and info levels. 22 | - Define traceable event logs and implement. 23 | 24 | ## Related design pattern 25 | - [Prediction log pattern](./../../Prediction-log-pattern/design_en.md) 26 | - [Prediction monitoring pattern](./../../Prediction-monitoring-pattern/design_en.md) -------------------------------------------------------------------------------- /Operation-patterns/Anti-patterns/No-logging-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # No logging pattern 2 | 3 | ## Case 4 | - ログやプロファイルを取得していない状態。 5 | 6 | ## Situation 7 | 機械学習システムに限らず、システムを運用するためにはログが必要です。ログを取得しない場合、エラー検知や障害対応、システム改善を行うことができず、ブラックボックスなシステムが醸成されていきます。特に機械学習システムでは、推論結果とその後のイベントをログから追跡することによって、推論モデルの効果をレビューすることが可能になります。
8 | 機械学習を実用化する面白くチャレンジングな点は、機械学習のアウトプットがビジネスやユーザ体験に密接に紐づくところです。推論は複雑な自動化を可能にします。頑張ってif-elseで記述することが難しいワークフローであっても、機械学習で解決できることがあります(解決できないこともあります)。そして実際のビジネスやユーザの行動、更には物理的な世界(IoTやEdge AI)に影響を与えるということは、変わり続ける環境にフィットしなければならないということで、機械学習やシステムの観点からすると、ログを収集して原因と結果と改善を続ける、ということになると思います。 9 | 10 | ## Diagram 11 | ![diagram](diagram.png) 12 | 13 | 14 | ## Pros 15 | - 強いて言えば、ログの費用が不要になる。 16 | 17 | ## Cons 18 | - システムを運用することができなくなる。 19 | 20 | ## Work around 21 | - 最低限、Fatal、Error、Warning、Infoレベルのログは取得する。 22 | - 追跡可能なイベントログを定義し実装する。 23 | 24 | ## Related design pattern 25 | - [Prediction log pattern](./../../Prediction-log-pattern/design_ja.md) 26 | - [Prediction monitoring pattern](./../../Prediction-monitoring-pattern/design_ja.md) -------------------------------------------------------------------------------- /Operation-patterns/Anti-patterns/No-logging-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # No logging pattern 2 | 3 | ## Case 4 | - 로그나 프로파일을 관리하지 않는 경우. 5 | 6 | ## Situation 7 | 머신러닝뿐만 아니라 모든 시스템 운영과 개선을 위해서 로그를 남기는 것은 정말 중요합니다. 로그가 없으면, 시스템을 마치 블랙박스처럼 만들어 에러를 찾고 트러블 슈팅을 하거나 환경 개선을 하는 것이 불가능해집니다. 특히, 머신러닝 시스템의 경우, 연관 이벤트 로그와 예측 결과를 통해 시스템과 모델을 개선할 수도 있고 비즈니스 계획에 도움을 줄 수 있습니다.
8 | 머신러닝 작업에서 흥미롭고 도전적인 부분은 머신러닝이 실제 비즈니스 분야나 사용자 경험과 밀접하게 관련되어 있다는 점입니다. 정교한 방식으로 어떠한 행동이나 자동화를 예측하는 것은 기존의 if-else 문 만으로는 실현하기 정말 어려운 것이었지만, 머신러닝을 통해서는 해결해 낼 수도 있습니다. 비즈니스나 사용자 행동 심지어 물리적인 환경(IoT나 EdgeAI)에 영향을 준다는 것은 계속 바뀌는 실제 환경에 적합해야 하고, 이는 모델과 시스템 입장에서 추적할 수 있어야 한다(로그를 수집해야 한다)는 점을 유의해야 합니다. 9 | 10 | ## Diagram 11 | ![diagram](diagram.png) 12 | 13 | 14 | ## Pros 15 | - 로그 보관 비용이 들지 않습니다. 16 | 17 | ## Cons 18 | - 시스템을 운영하거나 개선할 수 없습니다. 19 | 20 | ## Work around 21 | - 최소한의 Fatal, Error, Warning, Info 레벨의 로그는 남겨야 합니다. 22 | - 추적 가능한 이벤트 로그를 정의하고 구현해야 합니다. 23 | 24 | ## Related design pattern 25 | - [Prediction log pattern](./../../Prediction-log-pattern/design_en.md) 26 | - [Prediction monitoring pattern](./../../Prediction-monitoring-pattern/design_en.md) 27 | -------------------------------------------------------------------------------- /Operation-patterns/Anti-patterns/No-logging-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Operation-patterns/Anti-patterns/No-logging-pattern/diagram.png -------------------------------------------------------------------------------- /Operation-patterns/Anti-patterns/Nobody-knows-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Nobody knows pattern 2 | 3 | ## Case 4 | - A machine learing system is running in production, but the machine learning engineer, software engineer or operator has left the project, and nobody knows what the system is working for. 5 | - You can change a code, model and configuration without anybody's review. 6 | 7 | ## Situation 8 | Not only for a machine learning system, but for all the systems, it is a horror when nobody knows how it is working. It is a remedy if the system is running independently without any dependents and no business impact, but the condition that "nobody knows" means that you cannot assure it is actualy independent, and in the worst case, all of your services stop all the sudden.
9 | On the other hand, there is less probability that the same members are assigned to one same project. With some private or organizational reasons, some people may leave the project. However, business and system work independent from personal reasons. You can seldom stop your production system because one engineer left the company. You need to implement business continuity with considering risks of what would happen, and it is sharing and documenting of model logic, dataset, versioning, code and environmental configuration in a perspective of machine learning system. You may be able to understand your software with reading its source code, though machine learning model and training dataset cannot be reproduced if it is not stored and managed.
10 | The "nobody knows" pattern may occur not only on member's retirement. Let's suppose you are using a machine learning model in IoT system with thermometer device logs. This condition may be in factory or in your room. You can measure temperature in Celsius, Fahrenheit and Kelvin. The United States commonly use Fahrenheit, Japan uses Celsius, and science uses Kelvin. Converting Celsius to Fahrenheit changes numerical range, such that 0 degrees Celsius is 32 degrees Fahrenheit, and 100 Celsius is 212 Fahrenheit. If you need to change the unit measurement of your thermometer from Celsius to Fahrenheit, or to Kelvin, you have to change the unit in your machine learning model to predict accurately. You may be able to detect the anomaly for Celsius to Fahrenheit change, for the values change apparently, but what if it is change from meter to yard in distance. 1 meter is 1.09 yard, and this little change may not be detected even by humans. Using physical device or sensor in machine learning system is common in a certain industry, and changing the device configuration may be ignorant to impact on machine learning, as a "nobody knows" pattern. 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - Troubleshooting manias may have exciting moments. 18 | 19 | ## Cons 20 | - Difficulty in operating machine learning system. 21 | - Prediction may be erroneous. 22 | 23 | ## Work around 24 | - Avoid depending on a person. 25 | - Include measurement unit sensing. 26 | 27 | ## Related design pattern 28 | - [Prediction log pattern](./Operation-patterns/Prediction-log-pattern/design_en.md) 29 | - [Prediction monitoring pattern](./Operation-patterns/Prediction-monitoring-pattern/design_en.md) 30 | -------------------------------------------------------------------------------- /Operation-patterns/Anti-patterns/Nobody-knows-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Nobody knows pattern 2 | 3 | ## Case 4 | - モデルを開発したエンジニア、システム開発者、運用者が不在(または退職)により、稼働しているシステムを理解している人間がいなくなる状態。 5 | - 手動で誰のレビューもなくコードやモデル、データ、設定を変更できる状態。 6 | 7 | ## Situation 8 | 機械学習システムに限らず、稼働しているシステムが何故、どうやって動いているのか、誰も知らない状態は恐ろしいでしょう。単体で動いていて事業影響のないシステムであれば良いですが、「誰も知らない」ということは依存関係や事業影響の有無も正確に把握できていない可能性があり、停止した瞬間に事業が止まる、ということも考えられます。
9 | 他方でプロジェクトに同じメンバーが常にアサインされ続けることはありません。個人的または組織的な事情で不在になることがあります。しかしメンバーの出入りとシステムの稼働は別物です。担当者が退職したからといって急に事業用の本番システムを停止することは考えられません。機械学習のモデルやシステムについても同様で、メンバーが不在になったとしても開発や事業を維持できるよう、複数人でモデルのロジックおよびシステム構成、コードを共有し、引き継げることが理想です。最悪の場合、ソースコードは読めばわかるかもしれませんが、機械学習のモデルやトレーニングデータは管理されていないと復元不可能なことが多いでしょう。
10 | 「誰も知らない」状態はメンバーの出入り以外でも発生します。例えば物理デバイスのログをもとに推論している機械学習システムがあるとします。工場のラインや室内温度計が物理デバイスの例になるでしょう。温度は摂氏、華氏、ケルビンで計測することができ、日本では摂氏が一般的ですが、単位を華氏に換えると範囲が大きく変わります(摂氏0°は華氏32°、摂氏100°は華氏212°)。温度計の単位を変えて、入力データの計測単位を摂氏から華氏に換える場合、推論時に摂氏華氏変換を行っていないと(≒摂氏華氏変換を検知できないと)、推論結果は大きく変わると思われます。摂氏華氏変換であれば大きな値の変化となり、異常値検知が可能かもしれません。しかしメートルとヤードの変換(1メートル=1.09ヤード)の場合、差異が小さく済むため、もっともらしいログと推論が記録され、異常に気づかない可能性もあります。こうした物理デバイスの変換は機械学習システムを意識せず、利用者の利便性のために実施されるため、「誰も知らない」状態で推論が異常になることがあります。 11 | 12 | 13 | ## Diagram 14 | ![diagram](diagram.png) 15 | 16 | 17 | ## Pros 18 | - トラブルシューティングマニアであれば楽しめるでしょう。 19 | 20 | ## Cons 21 | - 機械学習システムの運用が困難になる。 22 | - 推論結果が異常になる。 23 | 24 | ## Work around 25 | - システムの開発、運用を個人に依存させない。 26 | - 入力データに計測単位を含める。 27 | 28 | ## Related design pattern 29 | - [Prediction log pattern](./Operation-patterns/Prediction-log-pattern/design_ja.md) 30 | - [Prediction monitoring pattern](./Operation-patterns/Prediction-monitoring-pattern/design_ja.md) 31 | -------------------------------------------------------------------------------- /Operation-patterns/Anti-patterns/Nobody-knows-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Nobody knows pattern 2 | 3 | ## Case 4 | - 머신러닝 시스템이 실제 운영 서비스에서 돌고 있지만 ML 엔지니어, 개발자, 운영자가 떠나 아무도 그 시스템이 무엇을 위해 작동하는지 모르는 경우. 5 | - 누구의 리뷰도 없이 코드, 모델 그리고 설정값을 변경할 수 있는 경우. 6 | 7 | ## Situation 8 | 머신러닝 시스템뿐만 아니라 가동되고 있는 시스템이 어떻게 동작하는지 아무도 모르는 경우는 항상 공포스럽습니다. 그 시스템이 아무런 의존성도 없고 비지니스에 아무런 영향이 없다면 좋겠지만, "아무도 모른다"라는 조건은 정말 이 시스템이 독립적인지 보장할 수 없으며 최악의 경우에는 모든 서비스가 갑자기 중단될 수도 있다는 것을 의미합니다.
9 | 또 다른 이유로 같은 프로젝트에 항상 같은 멤버가 배정되지 않는다는 것입니다. 사적인 이유나 조직적인 이유로도 사람들이 프로젝트를 떠날 수도 있습니다. 하지만 비즈니스와 시스템은 이러한 개인적인 이유와는 별개로 운영되어야 합니다. 담당 엔지니어가 한 명 그만두었다고 동작하고 있는 시스템이 중단되어서는 안 됩니다. 발생할 수 있는 리스크들을 고려하여 비즈니스가 계속될 수 있도록 구성해야 하며, 머신러닝 시스템 관점에서 모델 로직, 데이터 세트, 버전, 코드, 환경 구성 등을 공유하고 문서화하는 것이 좋습니다. 소프트웨어는 소스 코드를 읽어 이해할 수 있지만, 머신러닝 모델과 학습 데이터 세트는 제대로 저장되고 관리되지 않으면 복원이 불가능할 수도 있습니다.
10 | "nobody knows" pattern 은 구성원들의 부재를 통해서만 발생하는 것이 아닙니다. 온도계 장치 로그가 있는 IoT 시스템에서 머신러닝 모델을 사용하고 있다고 가정해 봅시다. 공장이나 여러분 방이 이러한 사용 예가 될 수 있겠죠. 온도는 섭씨와 화씨, 켈빈으로 측정할 수 있습니다. 미국은 보통 화씨, 한국과 일본은 섭씨, 그리고 과학계에서는 켈빈을 주로 사용하고 있습니다. 섭씨는 화씨로 변환하면 0도가 32도가 되고 100도는 212 화씨가 되는 등 숫자의 범위가 크게 바뀝니다. 만약 온도계의 단위를 섭씨에서 화씨 또는 켈빈으로 바꾸려면, 머신러닝 모델에서의 단위도 바꾸어야 예측이 정확하게 될 것입니다. 섭씨에서 화씨 변경은 값의 변화가 크기 때문에 변화를 쉽게 알아낼 수 있을 것입니다. 하지만 미터와 야드(1미터=1.09야드) 의 경우에는 차이가 크지 않기 때문에 사람이라도 이 변화를 알아채기 어려울 것입니다. 머신러닝을 물리적 기기나 센서에 사용되는 것은 이제 흔히 볼 수 있는 것으로, 기기 설정 변화가 머신 러닝에 제대로 반영되지 않는 것 역시 "nobody knows" pattern으로 볼 수 있습니다. 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - 트러블슈팅 매니아들은 즐거워할 것입니다. 18 | 19 | ## Cons 20 | - 머신러닝 시스템 운영의 어려움. 21 | - 예측 결과가 잘못될 수도 있습니다. 22 | 23 | ## Work around 24 | - 개인에게 의존시키지 않습니다. 25 | - 입력 데이터의 단위도 포함합니다. 26 | 27 | ## Related design pattern 28 | - [Prediction log pattern](./Operation-patterns/Prediction-log-pattern/design_en.md) 29 | - [Prediction monitoring pattern](./Operation-patterns/Prediction-monitoring-pattern/design_en.md) 30 | -------------------------------------------------------------------------------- /Operation-patterns/Anti-patterns/Nobody-knows-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Operation-patterns/Anti-patterns/Nobody-knows-pattern/diagram.png -------------------------------------------------------------------------------- /Operation-patterns/Anti-patterns/README.md: -------------------------------------------------------------------------------- 1 | # Operation Antipatterns 2 | 3 | - [No logging pattern](./No-logging-pattern/design_en.md) 4 | 5 | - [Nobody knows pattern](./Nobody-knows-pattern/design_en.md) 6 | -------------------------------------------------------------------------------- /Operation-patterns/Anti-patterns/README_ja.md: -------------------------------------------------------------------------------- 1 | # Operation Antipatterns 2 | 3 | - [No logging pattern](./No-logging-pattern/design_ja.md) 4 | 5 | - [Nobody knows pattern](./Nobody-knows-pattern/design_ja.md) 6 | -------------------------------------------------------------------------------- /Operation-patterns/Anti-patterns/README_ko.md: -------------------------------------------------------------------------------- 1 | # Operation Antipatterns 2 | 3 | - [No logging pattern](./No-logging-pattern/design_ko.md) 4 | 5 | - [Nobody knows pattern](./Nobody-knows-pattern/design_ko.md) 6 | -------------------------------------------------------------------------------- /Operation-patterns/Condition-based-serving-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Condition-based serving pattern 2 | 3 | ## Usecase 4 | - When prediction target varies a lot by condition. 5 | - When you can conditionally select a model in rule-based manner. 6 | 7 | ## Architecture 8 | The condition-based serving pattern is an architecture to select a model based on condition. You may have a situation where the prediction target varies depending on an user's condition, like time, place and persona. Say, you made a machine learning model to recommend a menu to your client. Recommending steak or wine for morning time is probably not adequate. Say, you made a camera-based product to classify a landmark building. There is very low probability that you classify a bridge in Japan as Golden Gate Bridge located in California. It is possible to separate target variables based on condition you run the prediction.
9 | You need to develop a prediciton service for each condition. The selection and distribution to each model will be controled in a proxy. The selection rule may depend on usecase: if you need to select based on time, you may need a morning model for morning, a noon model for noon, and a night model for night time. Difficulty of model development depends on how the problem space and target variable change with conditional change. If it is possible to share a feature engineering of one model with others, you may only need to update target variable for each condition. If the condition varies drastically that makes impossible to share, then you have to make independent models, or you may have not to choose this pattern. Since you will need to develop an overfitted model for each condition in the pattern, you may expect the model to predict better than a general model.
10 | If the number of models become too large, the amount of work you need for the model evaluation, improvement and management will increase that you may need to reconsider choosing the pattern in balance with cost is the right choice for your problem solving.
11 | Separating the condition depends on how the model input, feature and target vary. There may be a chance that you use a same model for morning and night time. On the other hand, it may cause an operational mistake if you make a conditional separation way different from person's understanding of condition. 12 | 13 | ## Diagram 14 | ![diagram](diagram.png) 15 | 16 | 17 | ## Pros 18 | - Select an adequate model depending on condition. 19 | 20 | ## Cons 21 | - Operational cost raise with number of models. 22 | 23 | ## Needs consideration 24 | - How to separate condition. 25 | - Balance between number of models and model management. 26 | 27 | ## Sample 28 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter6_operation_management/condition_based_pattern -------------------------------------------------------------------------------- /Operation-patterns/Condition-based-serving-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Condition-based serving pattern 2 | 3 | ## Usecase 4 | - 状況によって推論対象に大きな違いがある場合 5 | - 複数の推論モデルをルールベースで使い分け可能な場合 6 | 7 | ## Architecture 8 | 状況ベース推論パターンは状況に応じて実行する推論器を出し分けるものです。ユーザの状況(時間や場所、ペルソナ等)に応じて適切な推論対象が変わることがあります。例えばおすすめのメニューを機械学習で推薦するユースケースの場合、朝の時間帯にステーキやワインを推薦することが適切とは限らないでしょう。またはカメラを用いてランドマーク分類をする場合、日本にいるのにカリフォルニア州にあるゴールデンゲートブリッジを推論することは極めて稀です。推論対象が適切かどうか、状況に応じて使い分けるのが状況ベース推論パターンです。
9 | 状況ベース推論パターンでは各状況に応じてモデルを用意し、推論器としてデプロイします。各推論器へのアクセスはプロキシで制御します。時間帯によって出し分けるユースケースであれば、朝は朝専用モデル、昼は昼専用モデル、夜は夜専用モデルへリクエストします。モデル開発の難しさは各状況において問題空間や目的変数がどう変わるのか次第です。特徴エンジニアリングを共有できるのであれば目的変数のみを差し替えて学習することが可能です。状況によって特徴が大きく異なる場合は個別のモデル開発が必要になるでしょう。状況応じて過学習した推論モデルを用意することになるため、汎用的なモデルよりも適切な推論ができる、ということを期待したパターンになります。
10 | ただし、モデル数があまりにも多くなる場合、モデルの評価、改善や推論器の運用負荷が増大するため、状況ベース推論パターンで解決しようとしている課題が本当に本パターンや機械学習で解決すべきものなのか、コスト対効果から見直してみることも重要です。
11 | 状況の分割方法は、状況に応じたデータの特徴と目的変数次第になります。場合によっては朝と夜で同じ推論モデルを使うことが適切、ということもあり得るでしょう。他方で人間の感覚から離れた状況分解をすると、システム的な運用ミスを招く可能性もあるため、注意が必要です。 12 | 13 | ## Diagram 14 | ![diagram](diagram.png) 15 | 16 | 17 | ## Pros 18 | - 状況によって適切なモデルを提供することが可能。 19 | 20 | ## Cons 21 | - モデル数に応じて運用負荷が増大する。 22 | 23 | ## Needs consideration 24 | - 状況の分割方法。 25 | - モデル数と運用負荷のバランス。 26 | 27 | ## Sample 28 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter6_operation_management/condition_based_pattern -------------------------------------------------------------------------------- /Operation-patterns/Condition-based-serving-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Condition-based serving pattern 2 | 3 | ## Usecase 4 | - 상황 따라 예측해야 할 대상이 다양한 경우. 5 | - 룰 베이스의 방식으로 상황에 따라 모델을 선택해야 하는 경우. 6 | 7 | ## Architecture 8 | condition-based serving pattern은 상황에 따라 모델을 선택하는 구조입니다. 사용자의 상태(시간, 장소, 페르소나 등)에 따라 예측 대상이 바뀔 수 있는 경우들이 있습니다. 예를 들어, 고객에게 메뉴를 추천하기 위해 머신러닝 모델을 사용하는 경우, 스테이크나 와인을 아침 메뉴로 추천하는 것은 적절한 추천은 아닐 것입니다. 다른 예로. 카메라를 이용하여 랜드마크 빌딩을 분류하는 제품이 있을 경우, 일본에 있는 다리를 샌프란시스코의 금문교로 분류할 확률을 매우 낮을 것입니다. 예측을 하는 상황에 따라 타겟 변수를 구분할 수 있습니다.
9 | 각 상황에 따라 맞는 사용할 모델을 사용하도록 개발해야 합니다. 각 모델에 대한 선택과 분산 처리는 프록시를 통해 제어합니다. 사용 사례에 따라서 선택하는 규칙이 달라질 수 있습니다. 예를 들어, 시간을 기준으로 선택할 경우, 아침 전용, 점심 전용, 저녁 전용, 야간 전용과 같이 나눌 수 있습니다. 이 경우, 모델 개발에서 난이도는 각 상황에 따라 변하는 문제의 범위와 타겟 변수가 어떻게 바뀌느냐에 따라 달라질 수 있습니다. 한 모델의 피쳐 엔지니어링을 다른 모델과 공유할 수 있는 경우라면, 각 조건에 대한 타겟 변수만 업데이트하면 됩니다. 만약 상황이 크게 달라져서 서로 공유할 수 없다면, 독자적인 모델을 만들거나 다른 패턴을 따를 수 있습니다. 각각의 상황에 대해 충분히 학습된 모델을 만들게 되므로, 범용적인 모델보다 더 좋은 결과를 기대할 수 있습니다.
10 | 단, 모델수가 너무 많아지게 되면, 모델 평가, 개선, 운영에 필요한 작업량이 늘어나기 때문에 균형 잡힌 패턴을 선택하도록 고려해 봐야 할 수도 있습니다.
11 | 상황을 구분하는 것은 모델 입력, 피쳐, 타겟에 따라 다양하게 달라질 수 있습니다. 경우에 따라서는 아침과 밤에 같은 모델을 사용하는 것이 적절할 수도 있습니다. 다른 한편으로는, 상황 구분에 대한 이해도에 따라 운영상 실수를 만들 수도 있습니다 12 | 13 | ## Diagram 14 | ![diagram](diagram.png) 15 | 16 | 17 | ## Pros 18 | - 상황에 따라 알맞은 모델을 제공할 수 있습니다. 19 | 20 | ## Cons 21 | - 모델 수에 따라 운영 비용 증가. 22 | 23 | ## Needs consideration 24 | - 상황을 구분하는 방법 25 | - 모델 수와 모델 운영 사이의 균형 26 | 27 | 28 | ## Sample 29 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter6_operation_management/condition_based_pattern -------------------------------------------------------------------------------- /Operation-patterns/Condition-based-serving-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Operation-patterns/Condition-based-serving-pattern/diagram.png -------------------------------------------------------------------------------- /Operation-patterns/Data-model-versioning-pattern/diagram0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Operation-patterns/Data-model-versioning-pattern/diagram0.png -------------------------------------------------------------------------------- /Operation-patterns/Data-model-versioning-pattern/diagram1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Operation-patterns/Data-model-versioning-pattern/diagram1.png -------------------------------------------------------------------------------- /Operation-patterns/Model-in-image-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Model-in-image pattern 2 | 3 | ## Usecase 4 | - When you want to unify versions of service environment and prediction model. 5 | 6 | ## Architecture 7 | While productionizing an ml service on a cloud platform (or on containers) becomes a common practice, it is still an important consideration to manage and version machine learning model along with its server image. The easiest way to do so is by including the model file into the server or container image. In the model-in-image pattern, you build a server or container image with the model file contained in it. This aligns the model training and image building in one workflow. This also makes the image version and model version unique, this way their version alignment with each other is not lost.
8 | You build your image after the model training completes. To deploy the prediction service, you can then pull and run the image on the production platform.
9 | A difficulty of the pattern is that the image building latency tends to get long and image size increase. Since the image building starts once the training completes, you will want to make a workflow for this to go through without any errors or recoverables. Also its deployment time will be long as downloading an image takes long because of the image size. 10 | 11 | ## Diagram 12 | ![diagram](diagram.png) 13 | 14 | 15 | ## Pros 16 | - Uniquely identify a server image with model file version. 17 | 18 | ## Cons 19 | - You need to define a complete pipeline of a model training and image building. 20 | - Takes longer to build image and deploy. 21 | 22 | ## Needs consideration 23 | - Pipeline definition. 24 | 25 | ## Sample 26 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter3_release_patterns/model_in_image_pattern 27 | -------------------------------------------------------------------------------- /Operation-patterns/Model-in-image-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Model-in-image pattern 2 | 3 | ## Usecase 4 | - サーバイメージと推論モデルのバージョンを一致させたい場合 5 | 6 | ## Architecture 7 | クラウドやコンテナによってサーバイメージを使ってサーバを稼働させることが一般的になりましたが、機械学習の推論器としてサーバイメージと推論モデルファイルの管理方法やバージョニングは重要な検討課題です。サーバイメージに推論モデルファイルを含めて管理することが可能です。モデル・イン・イメージ・パターンでは推論サーバのイメージに学習済みモデルファイルを含めることによって、学習とサーバイメージ構築を一連のワークフローに組み込むことが可能になります。サーバイメージとモデルファイルのバージョンが同一となるため、ライブラリのバージョンによって稼働可能なモデルを選定する必要がなくなります。
8 | モデル・イン・イメージ・パターンでは学習によってモデルファイルを生成した後にモデルファイル含めて推論サーバイメージをビルドします。推論サーバを配備する際には、サーバイメージをPullして推論サーバを起動することで本稼働させることができます。
9 | このパターンの難点は、推論サーバイメージ構築の所要時間が長くなる傾向にあることと、容量が増加することです。モデルの学習が完了した後に推論サーバイメージを構築するため、全行程をエラーなく完了させるパイプラインが必要になります。また、サーバイメージの容量が増加することで、イメージをロードし稼働させるまでの所要時間が長くなることがあります。 10 | 11 | ## Diagram 12 | ![diagram](diagram.png) 13 | 14 | 15 | ## Pros 16 | - サーバイメージとモデルファイルのバージョンを同一に保つことが可能。 17 | 18 | ## Cons 19 | - モデル学習からサーバイメージ構築までのパイプラインを定義する必要あり。 20 | - 推論サーバイメージの構築やサーバ配備の所要時間が長くなる。 21 | 22 | ## Needs consideration 23 | - モデル学習からサーバイメージ構築までのパイプライン定義方法。 24 | 25 | 26 | ## Sample 27 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter3_release_patterns/model_in_image_pattern 28 | -------------------------------------------------------------------------------- /Operation-patterns/Model-in-image-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Model-in-image pattern 2 | 3 | ## Usecase 4 | - 서비스 환경과 모델의 버전을 통합 관리하는 경우. 5 | 6 | ## Architecture 7 | 클라우드 플랫폼이나 컨테이너를 이용한 서비스 운영은 이미 일반적이지만, 여전히 ML 모델을 서버 이미지로 관리하고 버전 관리하는 것은 중요한 고려 사항입니다. 서버나 컨테이너 이미지에 모델을 포함하여 관리하는 것도 하나의 방법입니다. model-in-image 패턴에서는 모델 파일을 서버 또는 컨테이너 이미지를 포함시켜 모델 학습과 이미지 빌드를 하나의 워크플로우로 만듭니다. 이 경우 이미지 버전과 모델 버전이 동일하기 때문에 각각의 버전 관리를 따로 하지 않아도 됩니다. 8 |
9 | 모델 학습이 끝난 다음 이를 포함한 이미지를 빌드합니다. 운영 플랫폼에서는 이 이미지를 pull하여 실행함으로써 서비스를 배포할 수 있습니다. 10 |
11 | 이 패턴의 난점은 이미지 사이즈가 증가하고 이미지 빌딩 시간이 길어지는 경향이 있다는 것입니다. 모델 학습이 완료된 후 이미지 빌드가 시작되기 때문에, 전 과정이 오류 없이 모두 통과되는 파이프라인 구축이 필요합니다. 또, 이미지 용량 증가로 이미지 다운로드가 길어지고 배포 시간도 길어질 수 있습니다. 12 | 13 | ## Diagram 14 | ![diagram](diagram.png) 15 | 16 | 17 | ## Pros 18 | - 서버 버전과 모델을 고유한 버전으로 동일하게 운영할 수 있습니다. 19 | 20 | ## Cons 21 | - 모델 학습과 이미지 빌드의 전체적인 파이프라인을 만들어야 합니다. 22 | - 이미지 빌드와 배포 시간이 길어질 수 있습니다. 23 | 24 | ## Needs consideration 25 | - 모델 학습부터 이미지 빌드까지의 파이프라인 정의 26 | 27 | 28 | ## Sample 29 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter3_release_patterns/model_in_image_pattern 30 | -------------------------------------------------------------------------------- /Operation-patterns/Model-in-image-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Operation-patterns/Model-in-image-pattern/diagram.png -------------------------------------------------------------------------------- /Operation-patterns/Model-load-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Model load pattern 2 | 3 | ## Usecase 4 | - When update cycle of a model is more frequent than server image update. 5 | - When you want to reuse a server image for serving multiple models. 6 | 7 | ## Architecture 8 | While productionizing an ml service on a cloud platform (or on containers) becomes a common practice, it is still an important consideration to manage and version machine learning model along with its server image. By building server (or container image) and model file separately, you may be able to decouple the management of the model and the server. In the model-load pattern, you build and save the prediction server image and model file separately, making the image light-weight with respect to size. It is also possible and responsible, to design the image for common use. Such a design allows reusing the same image on various prediction models, making this pattern highly effective when your models are compatible with the same image.
9 | To release a prediction service using this pattern, the prediction server needs to be deployed first into the platform, and then it downloads the model file as its initial task, before starting the prediction process. You may consider using an environmental variable to configure which model needs to be run on the server.
10 | A difficulty of the pattern is to manage dependent library for the models. You are required to match the library versions that the model uses and the ones that is installed in the image. It will be needed to make a table of supported libraries for each image and models, thus resulting in increase of operation. 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - Separate model versioning and image versioning. 18 | - Reuse of server image. 19 | - Light image size. 20 | - Change management of server image becomes easier. 21 | 22 | ## Cons 23 | - It may take longer to start the service. The server although up should be treated as unhealthy until the model load completes. 24 | - A new requirement of matching supported library versions between images and models is applicable for this pattern. 25 | 26 | ## Needs consideration 27 | - Dependent version management of server image and model file. 28 | 29 | ## Sample 30 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter3_release_patterns/model_load_pattern -------------------------------------------------------------------------------- /Operation-patterns/Model-load-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Model load pattern 2 | 3 | ## Usecase 4 | - サーバイメージのバージョンよりも推論モデルのバージョンを頻繁に更新する場合 5 | - 同一サーバイメージで複数種類の推論モデルを稼働させる場合 6 | 7 | ## Architecture 8 | クラウドやコンテナによってサーバイメージを使ってサーバを稼働させることが一般的になりましたが、機械学習の推論器としてサーバイメージと推論モデルファイルの管理方法やバージョニングは重要な検討課題です。サーバイメージと推論モデルファイルを分けて管理することによって、サーバイメージの構築(およびライブラリのバージョニング)とモデル学習を分離することができます。モデル・ロード・パターンでは推論サーバのイメージ構築とモデル学習の保存を別に実行することによって、サーバイメージを軽量にすることが可能になります。同時にサーバイメージの汎用性を高め、同一イメージを複数の推論モデルに応用することができます。複数の用途で同一のサーバイメージを利用する場合にこのパターンは有効です。
9 | モデル・ロード・パターンでは推論サーバを配備する際、サーバイメージをPullした後に推論サーバを起動し、その後にモデルファイルをロードして推論サーバを本稼働させます。モデルファイルのロード元を変数等で変更することによって、推論サーバで稼働するモデルを柔軟に変更することも可能です。
10 | このパターンの難点は、推論モデルがライブラリのバージョンに依存する場合、このパターンではサーバイメージのバージョン管理とモデルファイルのバージョン管理(サポートするライブラリのバージョン管理)を行う必要があることです。サーバイメージとモデルファイルのサポート表等が必要になるため、サーバイメージとモデルファイルが増え、複雑になっていくに従って、運用負荷が増大する可能性があります。 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - サーバイメージのバージョンとモデルファイルのバージョンを分離することが可能。 18 | - サーバイメージの応用性が向上。 19 | - サーバイメージが軽量になる。 20 | 21 | ## Cons 22 | - 推論サーバの起動に時間がかかる可能性がある(サーバの配備とモデルファイルのロードが順番に行われるため)。 23 | - サーバイメージとモデルファイルのバージョニングが必要。 24 | 25 | ## Needs consideration 26 | - サーバイメージとモデルファイルのバージョニング方法および依存関係の管理。 27 | 28 | ## Sample 29 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter3_release_patterns/model_load_pattern -------------------------------------------------------------------------------- /Operation-patterns/Model-load-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Model load pattern 2 | 3 | ## Usecase 4 | - 서버 이미지 업데이트보다 모델 업데이트가 더 잦은 경우. 5 | - 서버 이미지를 여러 모델에 재사용하려는 경우. 6 | 7 | ## Architecture 8 | 클라우드 플랫폼이나 컨테이너를 이용한 서비스 운영은 이미 일반적이지만, 여전히 ML 모델을 서버 이미지로 관리하고 버전 관리하는 것은 중요한 고려 사항입니다. 빌드 서버 혹은 컨테이너 이미지를 모델 파일과 별도로 사용하고 관리도 따로 할 수 있습니다. model-load pattern은 서버 이미지와 모델 파일을 별도로 작성하고 따로 실행함으로써 서버 이미지를 경량화할 수 있는 패턴입니다. 또, 서버 이미지의 범용성을 높여 동일 이미지로 여러 예측 모델에 재사용할 수 있습니다. 이 패턴은 모델들이 동일한 서버 이미지에 의존적일 때 유용합니다.
9 | 이 패턴에서 서비스를 릴리즈하려면, 먼저 예측 서버를 플랫폼에 배포한 다음, 프로세스의 시작으로 이미지 파일을 다운로드합니다. 서버에서 실행될 모델을 유연하게 구성을 위해 환경 변수를 이용할 수도 있습니다.
10 | 이 패턴의 단점은 모델이 라이브러리 버전에 의존적인 경우, 모델이 사용하는 라이브러리 버전과 이미지에 설치된 라이브러리 버전을 동일하게 관리해 주어야 한다는 것입니다. 서버 이미지와 모델 파일이 늘어나고 복잡해짐에 따라 운영 부하가 증가할 수 있습니다 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - 모델과 서버 이미지의 버전 구분. 18 | - 서버 이미지 재사용. 19 | - 서버 이미지 경량화. 20 | 21 | ## Cons 22 | - 서비스를 시작하는데 오래 걸릴 수 있습니다. (서버와 모델 파일 로드가 차례로 진행되기 때문에) 23 | - 이미지와 모델 지원 버전 관리. 24 | 25 | ## Needs consideration 26 | - 서버 이미지와 모델 파일의 버전 및 의존성 관리. 27 | 28 | 29 | ## Sample 30 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter3_release_patterns/model_load_pattern -------------------------------------------------------------------------------- /Operation-patterns/Model-load-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Operation-patterns/Model-load-pattern/diagram.png -------------------------------------------------------------------------------- /Operation-patterns/Parameter-based-serving-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Parameter-based serving pattern 2 | 3 | ## Usecase 4 | - To control prediction with parameter. 5 | - When it is possible to control rule-based. 6 | 7 | ## Architecture 8 | In general it is impossible to edit parameters in a trained model. On the other hand, a model may not always align with business logic or system requirement. For instance, if the model in production is giving negative effect on your business for some reason, you may need to update the model, or remove the prediction from the service. If it takes long to retrain the model and build it to production use, possibly you need to decide to remove the prediction temporalily. Or, there may be a chance that your prediction is anomaly only for a certain input data, and all the others are right. In that case, you still need to either retrain the model, or eliminate prediction for that particular kind of data. When you need to implement a machine learning prediction into a productiono service, it is not always the case that high accuracy results in good business impact, and you may need to consider an edge case or systematic issue, which may need to be mitigated in some rule-based ways.
9 | For those cases, it is useful to add a mechanism in your code to change behaviour of all or a part of the predictions, including stopping, retrying or timeout. You may use arguments to specify with execution command to control the change, or use environmental variables for container native application. Since it is difficult to keep high accuracy without any error for a model for every case or every input data, it is better to estimate possible anomaly and control with rulebased mechanism. On the other hand, it is impossible to cover all the abnormals. It may be good to have a `Activate` or not variable to just stop all the predictions to prevent worst case. 10 | 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - To avoid abnormal prediction for edge cases. 18 | 19 | ## Cons 20 | - Impossible to cover all the cases. 21 | - Increase in rules make complexity in operation. 22 | 23 | ## Needs consideration 24 | - Which cases to control with what variable. 25 | 26 | ## Sample 27 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter6_operation_management/paramater_based_pattern -------------------------------------------------------------------------------- /Operation-patterns/Parameter-based-serving-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Parameter-based serving pattern 2 | 3 | ## Usecase 4 | - 推論器を変数で制御したい場合 5 | - ルールベースで制御が必要な推論が存在する場合 6 | 7 | ## Architecture 8 | MLモデルは学習によってパラメータが固定されるため、一般的に学習後に個別に修正することはできません。他方でモデルの学習とビジネスロジックやシステム仕様が常に一致するとは限りません。例えば推論器が異常な推論を繰り返していてビジネスに悪影響がある場合、モデルを再学習して修正リリースするか、推論器を本番サービスから切り離す必要があります。再学習に時間を要する場合、一時的に切り離す判断も必要です。または一部のデータ集合のみ推論が異常で、他の集合は正常な場合もあります。その場合、やはり再学習するか、異常な集合のみを推論しないロジックが必要になります。本番サービスにMLモデルを組み込む場合、モデルの精度が良ければ成功するわけではなく、エッジケースやシステム的な事情でルールベースで対処が必要になることがあります。
9 | こうした場合に備えて、推論の停止や一部データの推論からの除外、リトライやタイムアウト等、システムの中で推論器を運用するために必要なロジックを埋め込んでおくと即時対応が可能になります。アプリケーションであれば実行コマンドで指定可能な変数を用意しておくと良いでしょう。コンテナ型のシステムであれば環境変数で指定することが一般的です。いずれにしても、どんなに高精度なMLモデルでも、すべてのエッジケースや将来発生する異常に対して正常な推論をすることは困難であるため、発生しうる異常はルールベースで制御できるようにしておくと運用が安定します。なお、すべて異常をルールベースでカバーできるわけではないため、最悪の場合は推論器への接続を停止できるよう、`ACTIVATE` 変数だけは用意しておくことを推奨します。 10 | 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - MLモデルが正常に推論できないエッジケースや異常値による不具合を回避することができる。 18 | 19 | ## Cons 20 | - すべてのケースをルールベースでカバーできるわけではない。 21 | - ルールベースによる制御が増えることによる複雑化。 22 | 23 | ## Needs consideration 24 | - どのケースをどういうルールと変数で対応するか。 25 | 26 | ## Sample 27 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter6_operation_management/paramater_based_pattern -------------------------------------------------------------------------------- /Operation-patterns/Parameter-based-serving-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Parameter-based serving pattern 2 | 3 | ## Usecase 4 | - 파라미터를 사용하여 예측을 제어하고 싶은 경우. 5 | - 룰 베이스로 제어가 가능한 경우. 6 | 7 | ## Architecture 8 | 일반적으로 학습된 모델의 경우 파라미터가 고정되어 있기 때문에, 학습 후 개별적으로 파라미터를 수정할 수 없습니다. 하지만 모델이 항상 비지니스 로직이나 시스템 조건에 부합한 것은 아닙니다. 예를 들어, 실제 운영이 되고 있는 모델이 어떠한 이유로 비즈니스에 부정적인 영향을 미치는 경우, 모델을 업데이터 하거나 서비스에서 제거해야 하는 경우가 있을 수도 있습니다. 만약 재학습에 시간이 오래 걸린다면, 우선 일시적으로 제거하는 경우들이 있을 수 있습니다. 혹은 특정 입력 데이터에 대해서만 이상하고 다른 데이터에 대해서는 문제가 없을 수도 있습니다. 이 경우, 예정대로 모델을 다시 학습시키거나, 특정 데이터에 대해서는 예측하지 않는 로직을 사용할 수도 있습니다. 실제 서비스에 머신러닝을 이용할 경우, 높은 정확도의 결과로 좋은 비지니스 영향을 주는 것은 항상 있는 것이 아니며 일부 케이스나 시스템적인 이슈가 있는 경우를 고려하여 룰 베이스로 대처가 필요한 경우가 있음을 고려해야 합니다.
9 | 이러한 경우를 대비하여, 예측의 일부 혹은 전체를 정지시키거나 재시도하거나 타임 아웃시킬 수 있는 등의 동작을 변경시킬 수 있는 장치를 코드에 넣어두면 유용하게 사용할 수 있습니다. 이러한 제어를 하기 위해 실행 명령어의 인수를 사용하거나, 컨테이너 어플리케이션이라면 환경 변수를 이용할 수도 있습니다. 모든 케이스와 입력값에 대해 오류 없이 높은 정확도를 유지하기는 어렵기 때문에, 룰 베이스의 장치를 이용하여 이상 징후를 예측하고 제어하는 것이 안정적으로 운영할 수 있는 방법입니다. 그렇다 하더라도, 모든 이상을 룰 베이스만으로는 커버할 수 없습니다. 최악의 경우를 막기 위해 `Activate` 혹은 비활성화 변수를 만들어 모든 예측을 멈출 수 있도록 하는 것이 좋습니다. 10 | 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - 엣지 케이스에 대한 비정상적인 예측을 피할 수 있습니다. 18 | 19 | ## Cons 20 | - 모든 케이스를 커버할 수는 없습니다. 21 | - 룰이 늘어남에 따라 운영의 복잡도가 올라갈 수 있습니다. 22 | 23 | ## Needs consideration 24 | - 어떠한 케이스를 어떤 변수로 제어 가능할지. 25 | 26 | ## Sample 27 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter6_operation_management/paramater_based_pattern 28 | -------------------------------------------------------------------------------- /Operation-patterns/Parameter-based-serving-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Operation-patterns/Parameter-based-serving-pattern/diagram.png -------------------------------------------------------------------------------- /Operation-patterns/Prediction-log-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Prediction log pattern 2 | 3 | ## Usecase 4 | - To use prediction, latency, and other logs for improving your service. 5 | - If you have a concern of amount of log to record on your DWH. 6 | - To monitor and send alert with log. 7 | 8 | ## Architecture 9 | It is mandatory to collect log to analyze and improve your service. The log may include prediction result along with input, latency, client event, and related activities. Even though each log may be produced in each system component, it is reasonable to record them in one DWH. Using queue to aggregate log may reduce overload to DWH without losing logs, while you may need to consider if the log processing takes so long that affects freshness of the log.
10 | Log is useful in many aspects. For instance, if the prediction or user behaviour is unexpected, or changed drastically from past, then you may assume there is some anomaly in a workflow. It is better to send an alert in such case to analyze anomaly and resolve it. There may be a chance that input data format changes with a little change in client code. If you can observe a system outage with that change, that is rather fortunate case. The model serving may predict without error, but with erroneous prediction. To filter such cases, it is good to have an alert for the prediction system as well as the model prediction log. 11 | 12 | 13 | ## Diagram 14 | ![diagram](diagram.png) 15 | 16 | 17 | ## Pros 18 | - Able to analyze effect of prediction. 19 | - Alert. 20 | 21 | ## Cons 22 | - Amount of log may increase cost. 23 | 24 | ## Needs consideration 25 | - Log frequency and log level. 26 | - Storing frequency and backup. 27 | - Purpose of analysis. 28 | 29 | ## Sample 30 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter5_operations/prediction_log_pattern -------------------------------------------------------------------------------- /Operation-patterns/Prediction-log-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Prediction log pattern 2 | 3 | ## Usecase 4 | - 推論結果や所要時間、ログをもとにサービスを改善したいとき 5 | - ログの発生量が多く、ログを集約するDWHへの負荷に懸念があるとき 6 | - ログを用いてアラートを送りたいとき 7 | 8 | ## Architecture 9 | MLシステムを組み込んだサービスを改善するためには推論結果や推論速度、クライアントへの影響、その後のイベントを収集し、分析する必要があります。各種ログはMLシステムの各コンポーネントで発生しますが、分析のためには統一したDWHに集約するほうが効率的です。DWHへはキューを通してログを追加することで、DWHへのアクセス負荷を軽減し、データロストを防ぐことができます。ただし、キューの処理時間が長引くと、DWHログの鮮度は低下します。
10 | ログは分析以外にも有用です。たとえばクライアントログや推論ログの結果が想定と違う(または従来から大きく変わった)場合、ワークフローとして異常が起きている可能性があります。そうした場合にはログからアラートを受け取り、異常を分析、解消する必要があります。クライアントの仕様変更により不意に入力データが変わってしまう、ということもあります。その場合に推論が失敗してシステム障害になれば気付くことが容易ですが、推論は通るけど結果が異常、ということもあり得ます。そうした場合に備えて、推論ログやクライアントログの異常状態を定義し、アラート対象にしておくことが重要です。 11 | 12 | 13 | ## Diagram 14 | ![diagram](diagram.png) 15 | 16 | 17 | ## Pros 18 | - 推論によるクライアントやユーザ、連携するシステムへの影響分析を実行することが可能。 19 | - 必要に応じてアラート可能。 20 | 21 | ## Cons 22 | - ログの量によってコストが増加する。 23 | 24 | ## Needs consideration 25 | - ログの収集頻度やログレベル 26 | - DWHへ格納する頻度や期間 27 | - 分析の目的 28 | 29 | ## Sample 30 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter5_operations/prediction_log_pattern -------------------------------------------------------------------------------- /Operation-patterns/Prediction-log-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Prediction log pattern 2 | 3 | ## Usecase 4 | - 서비스 개선을 위해 예측, 지연 시간 등 각종 로그를 사용하고자 할 때. 5 | - 방대한 로그량에 데이터 웨어하우스 부하가 우려될 때. 6 | - 로그를 사용하여 모니터링 및 알림을 보내고 싶을 때. 7 | 8 | ## Architecture 9 | 서비스 개선을 위해 로그를 수집하고 분석하는 것은 필수입니다. 입력, 지연 시간, 클라이언트 이벤트 및 관련 활동과 함께 예측 결과를 로그로 수집합니다. 로그들은 각각의 시스템 구성 내에서 생성되지만, 하나의 데이터 웨어하우스에 통합 관리하는 것이 효율적입니다. 큐 방식을 사용하면 로그 집계시 데이터 웨어하우스의 부하를 줄일 수 있습니다. 하지만 큐 처리 시간이 길어지게 되면 DHW 로그의 신선도(freshness)에 영향을 미칠 수 있습니다.
10 | 로그는 분석 이외에도 많은 면에서 유용합니다. 예를 들어, 예측이나 클라이언트 로그가 예상과 다르거나 과거의 패턴과 확연히 달라졌다면, 워크플로우에 이상이 생겼음을 예측할 수 있습니다. 이러한 경우 경고 알림을 보내 이상 현상을 분석하고 해결해야 합니다. 클라이언트 코드의 변경으로 인해 입력 데이터 형식이 변경되는 경우도 있습니다. 만약 그 변화로 시스템 장애가 난다면 차라리 운이 좋은 경우입니다. 모델 서빙에서 장애 없이 잘못된 예측으로 잘못된 결과를 만들어 낼 수도 있습니다.그러한 경우를 대비하여 예측 시스템 로그뿐만 아니라 클라이언트 로그에 대해서도 이상 상태를 정의하고 알림 대상으로 해 두는 것이 중요합니다. 11 | 12 | 13 | ## Diagram 14 | ![diagram](diagram.png) 15 | 16 | 17 | ## Pros 18 | - 예측 효과 분석 가능. 19 | - 경고 알람. 20 | 21 | ## Cons 22 | - 로그 양에 따라 비용이 증가할 수 있습니다. 23 | 24 | ## Needs consideration 25 | - 로그 수집 빈도와 로그 레벨 26 | - 저장 빈도와 백업. 27 | - 분석의 목적. 28 | 29 | ## Sample 30 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter5_operations/prediction_log_pattern 31 | -------------------------------------------------------------------------------- /Operation-patterns/Prediction-log-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Operation-patterns/Prediction-log-pattern/diagram.png -------------------------------------------------------------------------------- /Operation-patterns/Prediction-monitoring-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | Prediction monitoring pattern 2 | 3 | ## Usecase 4 | - When you want to monitor predictions and send alert if the trend is not expected. 5 | - To manage prediction trend and statistics. 6 | 7 | ## Architecture 8 | It is mandatory to take log and monitor infrastructure and application to operate the production service. It may be good to monitor prediction results as well, especially for a production system with service level to the model.
9 | In the prediction monitoring pattern, you will give monitor the inferences. There are multiple cases that the inference result may be suspicious. 10 | 11 | - When there is no inference for a target for a certain length of time, or when there is too many of them that should be rare. E.g. Too many anomalies detected on anomaly detection. 12 | - When there is too less, or too many, request compared to usual. E.g. 1000 requests per second happening on 100 rps expected service. E.g. No request for long in web service. 13 | - Continuous requests on a same input data. E.g. Retry occurring continuously for a certain input, or DDOS attack. 14 | 15 | In any case, it is necessary to analyze incident to normalize the service. To do so, you need to define the normal and abnormal conditions to monitor and alert. While it depends on the frequency of request, if it is rare to assume anomaly with few prediction in a web service. It is practical to observe from log in longer term to judge incident. In such case, you will monitor log storage or DWH to query regularly to see the change in trend. Or, you may need a dashboard to visualize logs.
16 | Configuration for monitoring and alert, with its operation, depends on service level of the prediction service. If it is critical to a large business or people's life, then it must make an alert on any small anomaly. In such case, its SRE must be supporting for 24/7. If the service is not so important, then alerting only daytime may be enough. You need to define operation based on service level of the system that makes monitoring and alerting configuration. It is important to make your team to work on the service level and importance of the service, not for all the alerts. 17 | 18 | 19 | ## Diagram 20 | ![diagram](diagram.png) 21 | 22 | 23 | ## Pros 24 | - Observe anomaly and start fixing an incident with alert. 25 | 26 | ## Cons 27 | - Unnecessary alert may cause increase in operational cost. 28 | 29 | ## Needs consideration 30 | - Service level. 31 | - Monitoring and alert configuration and operation based on the level. 32 | - Playbook. 33 | 34 | ## Sample 35 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter5_operations/prediction_monitoring_pattern -------------------------------------------------------------------------------- /Operation-patterns/Prediction-monitoring-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | Prediction monitoring pattern 2 | 3 | ## Usecase 4 | - 推論結果を監視し、推論傾向が異常な場合に通報したいとき 5 | - 推論の値や集計が想定された範囲内にあることを担保したいとき 6 | 7 | ## Architecture 8 | インフラやアプリケーションのログを監視し通報することは運用上必要なシステムになります。推論結果についても同様に監視したほうが良い場合があります。特に本番サービスやプロダクトに組み込まれている推論器や、推論結果にサービスレベル目標が定められている推論器の場合、推論傾向を監視することが求められます。
9 | 推論監視パターンでは推論器に注目して監視、通報を行います。推論結果の正常性が疑わしい状態には以下のようなものがあります。 10 | 11 | - 通常であれば発生する推論結果が一定時間発生しないとき(または滅多に発生しない推論結果が高頻度で発生するとき)。例:異常検知システムにおいて高頻度で異常が検知される場合。 12 | - 一定時間内の推論数が通常と比較して異常に少ないとき(または多いとき)。例:100rpsのサービスで推論が1000rps発生する場合。Webサービスで一定時間推論が実行されない場合。 13 | - 同じ入力データによる推論が連続して実行されているとき。例:特定の入力データでエラーになる推論でリトライが発生している場合。DDOS攻撃が実行されている場合。 14 | 15 | いずれの状態においても、推論器の異常または外部システムの異常を切り分け、正常化する必要があります。そのためには異常な状態(または正常な状態)を定義し、監視・通報するシステムが必要になります。推論器の実行頻度にもよりますが、Webサービスであれば数回の推論で異常と判断することは稀です。一定時間の推論から、異常な傾向があると判断する必要があります。その場合、監視対象は推論器ではなく、ログを集約するDWHに対して定期的にクエリして監視すると良いでしょう。または推論を視覚化するダッシュボードを用意する方法もあります。
16 | 監視・通報のレベルや頻度は推論器のサービスレベルや重要性次第です。大きなビジネス損失や人命に関わる推論器であれば、小さな異常でも高頻度で通報することになるかもしれません。その場合、運用担当者を24/365で配置する必要があります。逆に重要度の低いサービスであれば、日中のみの通報で、夜間は監視のみにしておくという体制も可能です。監視・通報に必要なのはサービスレベルに応じた運用方針になります。推論器やサービスの重要性を吟味し、体制を作ることが重要です。 17 | 18 | 19 | ## Diagram 20 | ![diagram](diagram.png) 21 | 22 | 23 | ## Pros 24 | - 推論器の異常に気付き、遅滞なく修正や障害対応することができる。 25 | 26 | ## Cons 27 | - 不要な監視・通報はコスト増の原因になる。 28 | 29 | ## Needs consideration 30 | - 推論器のサービスレベル 31 | - 監視・通報の頻度やレベル、通報先、体制 32 | - 異常時の対応方法やマニュアル 33 | 34 | ## Sample 35 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter5_operations/prediction_monitoring_pattern -------------------------------------------------------------------------------- /Operation-patterns/Prediction-monitoring-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Prediction monitoring pattern 2 | 3 | ## Usecase 4 | - 예측값을 모니터링하고 예측값이 예상과 다르게 나타날 경우 알림을 받고 싶을 때. 5 | - 예측값 트렌드와 통계 관리용. 6 | 7 | ## Architecture 8 | 실제 서비스를 운영하기 위해서 로그를 수집하고 인프라와 어플리케이션을 모니터링하는 것은 필수입니다. 특히, 서비스 레벨의 모델을 사용하는 실제 운영 시스템은 예측 결과에 대해서도 모니터링하는 것이 좋습니다.
9 | prediction monitoring pattern에서는 예측을 주로 모니터링합니다. 예측 결과가 의심스러운 경우는 다음과 같이 다양한 케이스가 있습니다. 10 | 11 | - 일정 시간 동안 대상에 대한 예측 결과가 없거나, 적어야 할 결과가 너무 많은 경우. 예 : 이상 징후 감지가 너무 많이 탐지된 경우. 12 | - 평소보다 요청이 너무 적거나 너무 많을 때. 예: 100 rps 예상되는 서비스에서 초당 1000건 이상의 요청을 받을 때. 웹서비스에서 오랫동안 요청이 하나도 들어오지 않을 때. 13 | - 동일한 입력값으로 지속적으로 요청이 들어올 때. 예: 특정 입력값으로 계속 재시도가 발생하거나 DDOS 공격. 14 | 15 | 위와 같은 경우, 서비스 정상화를 위해 사건 분석을 해야 합니다. 이 분석을 위해, 정상과 비정상 상태를 정의하여 모니터링하고 감시할 필요가 있습니다. 요청 빈도에 따라 다르지만, 웹 서비스에서 요청이 적은 것을 이상한 상태라고 판단하기는 어렵습니다. 이러한 판단하기 위해서 장기적으로 로그를 관찰하여 비정상적인 경향을 알아내야 합니다. 이 경우, 로그 저장소나 데이터 웨어하우스에 정기적으로 쿼리하여 트렌드를 모니터링하는 것이 좋습니다. 또는 로그를 시각화하는 대시보드를 사용하는 방법도 있습니다.
16 | 모니터링과 알림 설정과 운영은 서비스 레벨이나 중요성에 따라 달라질 수 있습니다. 예를 들어, 큰 비즈니스이거나 사람의 목숨에 관련된 중요한 것이라면, 작은 이상이라도 알림이 가도록 정해야 합니다. 또, 이 경우의 SRE(Site Reliability Engineering)는 24/7으로 지원되어야 합니다. 반대로 중요도가 낮은 서비스라면, 낮에 알림 받는 것만으로도 충분할 수 있습니다. 모니터링 및 알림 구성을 만드는 시스템은 서비스 레벨에 맞게 작업을 정의되어야 합니다. 모든 알림에 대해서가 아니라 서비스 레벨과 중요성에 따라 작업하는 것이 중요합니다. 17 | 18 | 19 | ## Diagram 20 | ![diagram](diagram.png) 21 | 22 | 23 | ## Pros 24 | - 이상 징후를 탐지하고 알림과 함께 장애를 대응할 수 있습니다. 25 | 26 | 27 | ## Cons 28 | - 불필요한 알림으로 인해 운용 비용이 증가할 수 있습니다. 29 | 30 | ## Needs consideration 31 | - 서비스 레벨. 32 | - 모니터링 및 알람. 33 | - 레벨에 따른 설정과 운영. 34 | - 대응 방법. 35 | 36 | 37 | ## Sample 38 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter5_operations/prediction_monitoring_pattern -------------------------------------------------------------------------------- /Operation-patterns/Prediction-monitoring-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Operation-patterns/Prediction-monitoring-pattern/diagram.png -------------------------------------------------------------------------------- /Operation-patterns/README.md: -------------------------------------------------------------------------------- 1 | # Operation patterns 2 | 3 | - [Model-in-image pattern](./Model-in-image-pattern/design_en.md) 4 | 5 | 6 | - [Model-load pattern](./Model-load-pattern/design_en.md) 7 | 8 | 9 | - [Data model versioning pattern](./Data-model-versioning-pattern/design_en.md) 10 | 11 | 12 | - [Prediction log pattern](./Prediction-log-pattern/design_en.md) 13 | 14 | 15 | - [Prediction monitoring pattern](./Prediction-monitoring-pattern/design_en.md) 16 | 17 | 18 | - [Parameter-based serving pattern](./Parameter-based-serving-pattern/design_en.md) 19 | 20 | 21 | - [Condition-based-serving pattern](./Condition-based-serving-pattern/design_en.md) 22 | 23 | - [Antipatterns](./Anti-patterns/README.md) 24 | 25 | - [No logging pattern](./Anti-patterns/No-logging-pattern/design_en.md) 26 | 27 | - [Nobody knows pattern](./Anti-patterns/Nobody-knows-pattern/design_en.md) 28 | -------------------------------------------------------------------------------- /Operation-patterns/README_ja.md: -------------------------------------------------------------------------------- 1 | # Operation patterns 2 | 3 | - [Model-in-image pattern](./Model-in-image-pattern/design_ja.md) 4 | 5 | 6 | - [Model-load pattern](./Model-load-pattern/design_ja.md) 7 | 8 | 9 | - [Data model versioning pattern](./Data-model-versioning-pattern/design_ja.md) 10 | 11 | 12 | - [Prediction log pattern](./Prediction-log-pattern/design_ja.md) 13 | 14 | 15 | - [Prediction monitoring pattern](./Prediction-monitoring-pattern/design_ja.md) 16 | 17 | 18 | - [Parameter-based serving pattern](./Parameter-based-serving-pattern/design_ja.md) 19 | 20 | 21 | - [Condition-based-serving pattern](./Condition-based-serving-pattern/design_ja.md) 22 | 23 | - [Antipatterns](./Anti-patterns/README_ja.md) 24 | 25 | - [No logging pattern](./Anti-patterns/No-logging-pattern/design_ja.md) 26 | 27 | - [Nobody knows pattern](./Anti-patterns/Nobody-knows-pattern/design_ja.md) 28 | -------------------------------------------------------------------------------- /Operation-patterns/README_ko.md: -------------------------------------------------------------------------------- 1 | # Operation patterns 2 | 3 | - [Model-in-image pattern](./Model-in-image-pattern/design_ko.md) 4 | 5 | 6 | - [Model-load pattern](./Model-load-pattern/design_ko.md) 7 | 8 | 9 | - [Data model versioning pattern](./Data-model-versioning-pattern/design_ko.md) 10 | 11 | 12 | - [Prediction log pattern](./Prediction-log-pattern/design_ko.md) 13 | 14 | 15 | - [Prediction monitoring pattern](./Prediction-monitoring-pattern/design_ko.md) 16 | 17 | 18 | - [Parameter-based serving pattern](./Parameter-based-serving-pattern/design_ko.md) 19 | 20 | 21 | - [Condition-based-serving pattern](./Condition-based-serving-pattern/design_ko.md) 22 | 23 | - [Antipatterns](./Anti-patterns/README.md) 24 | 25 | - [No logging pattern](./Anti-patterns/No-logging-pattern/design_ko.md) 26 | 27 | - [Nobody knows pattern](./Anti-patterns/Nobody-knows-pattern/design_ko.md) 28 | -------------------------------------------------------------------------------- /QA-patterns/Anti-patterns/Offline-only-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Offline only pattern 2 | 3 | ## Case 4 | - If your machine learning model is only evaluated with offline test data. 5 | 6 | ## Situation 7 | A business value of a machine learning model can be proven when the model is implemented to your production service, and improves business KPI or contribute on efficiency. The model's utility can only be actually evaluated based on business, and it is not test data. The test dataset can be one of the criteria to decide releasing the model or not into production, but the test dataset is not business KPI. Even if your model scores 99.99% accuracy in a test dataset, you always have to reevaluate its actual impact in the business production environment to see if it makes improvement. If the model performs poor in the production, or make something worse, then it is recommended to decide shut down request to the model (with [Parameter-based serving pattern](../../../Operation-patterns/Parameter-based-serving-pattern/design_en.md)) to avoid anymore negative impact. 8 | 9 | ## Diagram 10 | ![diagram](diagram.png) 11 | 12 | 13 | ## Pros 14 | - None. 15 | 16 | ## Cons 17 | - You are not evaluating the model with your business impact. 18 | 19 | ## Work around 20 | - Define KPI to be improved with the model in production, and analyse comparison of the prereleased state and released state (or A group and B group for A/B testing). Configure log definition to evaluate the model impact, and once enough logs are collected to evaluate the model, assess the model to decide continue using the model or not. If continued, then let's see how to improve the model. 21 | 22 | ## Related design pattern 23 | - [Shadow AB-testing pattern](./../../Shadow-ab-test-pattern/design_en.md) 24 | - [Online AB-testing pattern](./../../Online-ab-test-pattern/design_en.md) -------------------------------------------------------------------------------- /QA-patterns/Anti-patterns/Offline-only-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Offline only pattern 2 | 3 | ## Case 4 | - 機械学習のモデルをオフラインのテストデータでしか評価していない状態。 5 | 6 | ## Situation 7 | 機械学習のモデルがビジネス的な価値を発揮するのは本番システムに組み込まれ、事業や効率化に貢献するときです。モデルが有用かどうか判断するのは事業や効率化の効果であって、テストデータではありません。テストデータはモデルをリリース可能かどうか判断する指標の一つにはなりますが、ビジネス上の評価にはなりません。テストデータで99.99%の正解率を得ていても、オンラインの実データで効果を発揮できないのであれば(または悪影響を及ぼすのであれば)、モデルは不要でしょう。推論器としてリリースしたモデルは実用の中で効果検証する必要があります。もしモデルがビジネスに悪影響を与え続けているようであれば、まずはモデルへのリクエストを停止して、モデルを使っていなかったときの状態に戻すことを推奨します([Parameter-based serving pattern](../../../Operation-patterns/Parameter-based-serving-pattern/design_ja.md)を使うと簡単に切り戻すことができます)。 8 | 9 | ## Diagram 10 | ![diagram](diagram.png) 11 | 12 | 13 | ## Pros 14 | - 特になし。 15 | 16 | ## Cons 17 | - 推論器を本来の指標で評価できない。 18 | 19 | ## Work around 20 | - モデルをリリースすることで得られる効果を定量的に定義し、リリース前とリリース後(またはA/BテストのA郡とB郡)を分割し、評価に必要なログを設計、収集し、一定期間後に効果検証を行い、推論器の維持または停止を判断する。 21 | 22 | ## Related design pattern 23 | - [Shadow AB-testing pattern](./../../Shadow-ab-test-pattern/design_ja.md) 24 | - [Online AB-testing pattern](./../../Online-ab-test-pattern/design_ja.md) -------------------------------------------------------------------------------- /QA-patterns/Anti-patterns/Offline-only-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Offline only pattern 2 | 3 | ## Case 4 | - 머신러닝 모델이 오프라인 테스트 데이터로만 평가되는 경우. 5 | 6 | ## Situation 7 | - 머신러닝 모델의 비즈니스 가치는 모델이 프러덕션 서비스에 구현될 때 입증될 수 있으며, 비즈니스 KPI를 개선하거나 효율성에 기여할 수 있습니다. 모델이 유용한지 결정하는 것은 실제로 비즈니스를 기준으로만 평가할 수 있으며 테스트 데이터에선 평가할 수 없습니다. 테스트 데이터 세트는 모델 출시 여부를 결정하는 기준 중 하나일 수 있지만 테스트 데이터는 비즈니스 KPI가 아닙니다. 테스트 데이터세트에서 모델이 99.99%의 정확도를 기록하더라도 실제 데이터에서 효과를 발휘하지 않는다면(또는 부정적인 영향을 미친다면) 이 모델은 유효하다고 할 수 없습니다. 예측 모델로 출시한 모델은 운영 환경에서 효과를 검증해야 합니다. 만약 모델이 운영 환경에서 성능이 저조하거나 더 나빠질 경우 모델에 대한 요청을 중지하고 모델을 사용하지 않았을 때로 되돌리는 것을 권장합니다. [Parameter-based serving pattern](../../../Operation-patterns/Parameter-based-serving-pattern/design_ko.md)를 사용하면 부정적인 영향을 피하며 쉽게 되돌릴 수 있습니다. 8 | 9 | ## Diagram 10 | ![diagram](diagram.png) 11 | 12 | 13 | ## Pros 14 | - 없습니다. 15 | 16 | ## Cons 17 | - 비즈니스에 미치는 영향을 기준으로 모델을 평가하지 않습니다. 18 | 19 | ## Work around 20 | - 프러덕션 모델로 개선할 KPI를 정의하고, 출시 전 상태와 출시 상태(A/B 테스트의 경우 A 그룹과 B 그룹)의 비교를 분석합니다. 모델 영향을 평가하기 위해 로그를 정의하고, 모델을 평가하기 위해 충분한 로그가 수집되면 모델을 평가해 모델을 계속 사용할지 여부를 결정합니다. 계속 사용한다면, 모델을 개선하는 방법을 찾아봅시다. 21 | 22 | ## Related design pattern 23 | - [Shadow AB-testing pattern](./../../Shadow-ab-test-pattern/design_ko.md) 24 | - [Online AB-testing pattern](./../../Online-ab-test-pattern/design_ko.md) 25 | -------------------------------------------------------------------------------- /QA-patterns/Anti-patterns/Offline-only-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/QA-patterns/Anti-patterns/Offline-only-pattern/diagram.png -------------------------------------------------------------------------------- /QA-patterns/Anti-patterns/README.md: -------------------------------------------------------------------------------- 1 | # QA Antipatterns 2 | 3 | - [Offline-only pattern](./Offline-only-pattern/design_en.md) -------------------------------------------------------------------------------- /QA-patterns/Anti-patterns/README_ja.md: -------------------------------------------------------------------------------- 1 | # QA Antipatterns 2 | 3 | - [Offline-only pattern](./Offline-only-pattern/design_ja.md) -------------------------------------------------------------------------------- /QA-patterns/Anti-patterns/README_ko.md: -------------------------------------------------------------------------------- 1 | # QA Antipatterns 2 | 3 | - [Offline-only pattern](./Offline-only-pattern/design_ko.md) -------------------------------------------------------------------------------- /QA-patterns/Loading-test-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Loading test pattern 2 | 3 | ## Usecase 4 | - To measure latency of prediction service. 5 | - To run load test on the prediction service to plan required resource for the production. 6 | 7 | ## Architecture 8 | The response latency and number of simultaneous connection available on prediction server are very important factors to maintain the service availability. Even if you develop a brilliant ML model, taking one minute to respond one request, or one request per server, may probably not work on the production service. Of course it can be worked around with a large scale resource or inference GPU as a platform, though it may not as business.
9 | The loading test pattern will give high load on the ML prediction service, just like it has been done on the general web or online service. Taking the prediction service is one form of the web or online service, you can apply the load test in a same manner. While most of the prediction services tend to be dependent on CPU for its performance, if the service cannot afford to succeed in latency or availability requirement, you have to increase the number of CPU core or server. In addition, if you develop the serving application with Python, you may suspect the service is running on one CPU per process, making inefficient use of the resource. In that case, you may need to consider using multiprocessing, wsgi or asgi to fully use resources.
10 | It is also important to consider a form of input data for the load test. Some predictions may use image, sound, movie or test, which tends to be large sized. If the size of a input image is random in the production environment, it is better to try simulating the randomness of the input data size, with variety of pixel and ratio. Those input data may be managed in the preprocess, and if the input data is so large that cannot be loaded to the RAM, it may cause Out-of-memory error to fail the server. In that case, you need to consider restructuring the preprocess or limit the input size.
11 | There may be a possibility that the bottleneck exists in a load balancer, network, proxy or even the load testing environment. If you cannot achieve your required latency or availability, it is better to go over the resources you are using for the load test. 12 | 13 | 14 | ## Diagram 15 | ![diagram](diagram.png) 16 | 17 | 18 | ## Pros 19 | - You can measure latency as well as the number of simultaneous connections to plan resource for the production environment. 20 | - You may be able to get troubleshooting skills and find bottleneck before going into the production service. 21 | 22 | ## Cons 23 | - Cost. 24 | - Difficult to tune model prediction speed. 25 | 26 | ## Needs consideration 27 | - Bottleneck and work around. 28 | - It is recommended to prepare a variety of dataset. 29 | - If the bottleneck is in model prediction, you may need to redevelop the model. 30 | 31 | ## Sample 32 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter6_operation_management/load_test_pattern 33 | -------------------------------------------------------------------------------- /QA-patterns/Loading-test-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Loading test pattern 2 | 3 | ## Usecase 4 | - 推論サーバのレスポンススピードを測りたいとき 5 | - 推論サーバのアクセス負荷試験を行い、本番環境に必要なリソースを計測したいとき 6 | 7 | ## Architecture 8 | 推論サーバのレスポンススピードや同時アクセス可能数はサービスの可用性に直結する重要な数値です。どんなに良い機械学習モデルを用意したとしても、1レスポンスに1分かかったり、1サーバが1リクエストしか受け付けられないという場合、サービスとして成立しません。もちろん大規模なリソースや推論用GPUを用意すれば可用性を担保することができるかもしれませんが、ビジネスとして成り立たない可能性もあります。
9 | 負荷試験パターンは、従来のWebサービスやオンラインシステムに行っていた負荷試験を機械学習推論サービスに対しても実施するものです。推論サービスをWebサービスやオンラインシステムと捉えれば、同様の方法論で負荷試験を行うことができます。機械学習の推論サービスは多くの場合、処理速度がCPU依存になることが多いため、スピードや同時リクエスト数が目標を満たさない場合、CPUやサーバ台数の調整を行う必要があります。また、Pythonで推論サービスを構築している場合、Pythonは1プロセス=1スレッドで稼働し、Global interpreter lockの制約を受けるため、リソースを有効活用できないことがあります。その場合、マルチプロセスやwsgi等のライブラリで同時実行数を増やす必要があります。
10 | 加えて機械学習の負荷試験時に検討すべきは入力データの種類です。サービスによっては画像や音声、動画、テキストといった容量の大きいデータを入力とする場合があります。本番サービスで1枚の画像サイズや音声サイズがランダムな場合、負荷試験でもサイズの長短をランダムに実行する(または最大サイズを入力する)必要があります。入力データは前処理で調整することになりますが、例えば入力データサイズが大きすぎてメモリに乗り切らず、Out-of-memoryでサーバが停止する可能性もあります。そうした場合は前処理の方法やリクエスト前にクライアントでサイズ制限を追加する必要があります。
11 | その他Webサービスの場合、ロードバランサーやネットワーク、または負荷試験サーバ側にボトルネックが存在する可能性もあります。期待するレスポンススピードや同時アクセス数を満たせない場合、負荷試験を構成する各リソースを鳥瞰することが重要です。 12 | 13 | ## Diagram 14 | ![diagram](diagram.png) 15 | 16 | 17 | ## Pros 18 | - 推論サーバのレスポンススピードや同時アクセス可能数を計測することで、リソース調整や可用性を定義することができる。 19 | - 本番で障害発生時の事前知識を溜めることができる。 20 | 21 | ## Cons 22 | - 負荷テストのコスト。 23 | - 推論モデルのチューニングは難しい。 24 | 25 | ## Needs consideration 26 | - システムのボトルネックとなる箇所 27 | - 多種多様な入力データを用意すること 28 | - 推論モデル自体が遅い場合、モデルの再開発が必要。 29 | 30 | ## Sample 31 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter6_operation_management/load_test_pattern 32 | -------------------------------------------------------------------------------- /QA-patterns/Loading-test-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Loading test pattern 2 | 3 | ## Usecase 4 | - 예측 서버의 대기 시간을 측정하고 싶은 경우. 5 | - 운영 환경에 필요한 리소스를 계획하기 위해 예측 서비스에서 부하 테스트를 실행하고 싶은 경우. 6 | 7 | ## Architecture 8 | 예측 서버의 대기 시간과 동시 연결 수는 서비스의 가용성에 직결되는 중요한 수치입니다. 아무리 좋은 머신러닝 모델을 만들어도 하나의 요청을 예측하는데 1분이 걸리거나 서버당 하나의 요청만 가능하다면 프러덕션 서비스에서 작동하지 않을 수 있습니다. 물론 대규모 리소스와 예측용 GPU를 사용해 플랫폼으로는 작업이 가능할 수 있지만, 비즈니스는 아닐 수 있습니다.
9 | 10 | Loading test pattern은 기존 웹 서비스나 온라인 시스템의 부하 테스트를 머신러닝 예측 서비스에 적용하는 패턴입니다. 예측 서비스는 웹 또는 온라인 서비스의 한 형태이므로 동일한 방식으로 부하 테스트를 적용할 수 있습니다. 대부분 예측 서비스의 성능은 CPU에 의존적이기 때문에, 만약 서비스가 대기 시간 또는 가용성 요구 사항을 만족하기 힘든 경우 CPU 코어 또는 서버 수를 늘려야 합니다. 추가로 만약 파이썬으로 예측 서버를 구축하는 경우, 파이썬은 하나의 프로세스에 하나의 쓰레드만 사용하는 GIL(Global Interpreter Lock)의 제약을 받기 때문에 리소스를 효율적으로 사용하지 못할 수 있습니다. 이런 경우 멀티프로세싱, wsgi 또는 asgi 사용해서 동시성을 늘려야 합니다.
11 | 12 | 부하 테스트를 위한 입력 데이터의 종류를 고려하는 것도 중요합니다. 일부 예측은 이미지, 소리, 영상 또는 텍스트를 사용할 수 있으며 이런 데이터들은 보통 크기가 큰 경향이 있습니다. 운영 환경에서 입력 이미지의 크기가 무작위인 경우 다양한 픽셀 및 비율로 입력 데이터 크기를 무작위로 시뮬레이션하는 것이 좋습니다. 이런 입력 데이터는 전처리 과정에서 관리될 수 있으며, 입력 데이터가 너무 커서 메모리에 로드할 수 없는 경우 메모리 부족 오류로 인해 서버가 중지될 수 있습니다. 이 경우 전처리를 재구성하거나 입력 데이터의 사이즈를 제한해야 합니다.
13 | 14 | 로드 밸런서, 네트워크, 프록시 또는 로드 테스트 환경에 병목 현상이 있을 수 있습니다. 필요한 대기 시간과 가용성을 달성할 수 없는 경우 부하 테스트에 사용 중인 리소스를 검토하는 것이 좋습니다. 15 | 16 | 17 | ## Diagram 18 | ![diagram](diagram.png) 19 | 20 | 21 | ## Pros 22 | - 운영 환경에 대한 리소스를 계획하기 위해 대기 시간과 동시 연결 수를 측정할 수 있습니다. 23 | - 운영 서비스에 들어가기 전에 트러블슈팅 스킬을 습득하고 병목 현상을 찾을 수 있습니다. 24 | 25 | ## Cons 26 | - 비용. 27 | - 모델 예측 속도 튜닝이 어렵습니다. 28 | 29 | ## Needs consideration 30 | - 병목 현상 및 해결 방법. 31 | - 다양한 데이터셋 준비를 추천합니다. 32 | - 병목 현상이 모델 예측에 있는 경우 모델을 다시 개발해야할 수 있습니다. 33 | 34 | 35 | ## Sample 36 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter6_operation_management/load_test_pattern 37 | -------------------------------------------------------------------------------- /QA-patterns/Loading-test-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/QA-patterns/Loading-test-pattern/diagram.png -------------------------------------------------------------------------------- /QA-patterns/Online-ab-test-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Online AB test pattern 2 | 3 | ## Usecase 4 | - To confirm the a new prediction model works with the production data. 5 | - To verify a new prediction server can load the production access. 6 | - To test business impact of the model in production. 7 | - To test the model will not worsen the impact than the current one. 8 | 9 | ## Architecture 10 | The online AB test pattern is an architecture to verity multiple prediction models with the production data and load. In this pattern, you will deploy multiple prediction services parallelly, load balance among them, keeping higher load on the current model, and gradually increase the access to the new server. The load balancing will be managed in the proxy server. The proxy will gather the request data and prediction with identity, and record them in a DWH. You may need to trace the client event log to compare the impact of the new model. The load balancing rule may be considered depending on the objective. If your aim is to compare user activity, it might be better to assign users to a constant model. If your aim is to log the prediction result, you may choose to randomly balance or send request to all the predictions.
11 | If it happens to have problem in prediction, latency or availability, it is better to decide eliminating the new model. You need to consider the term of testing. If the service has seasonal effect, you may need to run longer term, while if the service is used everyday in similar manner, the performance can be concluded in a few week. There may be a chance that you may find the result in shorter term. It is important to decide go or no go based on the effect of the new model replacing the current one.
12 | You will let the new model to be online with responding the prediction to the client. It is important to note that it will affect business or user experience. 13 | 14 | ## Diagram 15 | ![diagram](diagram.png) 16 | 17 | 18 | ## Pros 19 | - You can verity the new model performance without affecting the production service. 20 | - It is possible to record multiple predictions. 21 | 22 | ## Cons 23 | - It may make a negative impact on your business if the model or server is not good. 24 | - Additional cost 25 | 26 | ## Needs consideration 27 | - Load balancing policy. 28 | - Evaluation and decision policy of go or no go for the new model. 29 | 30 | ## Sample 31 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter6_operation_management/online_ab_pattern -------------------------------------------------------------------------------- /QA-patterns/Online-ab-test-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Online AB test pattern 2 | 3 | ## Usecase 4 | - 新推論モデルが本番データで問題なく推論できることを確認したいとき 5 | - 新推論サーバが本番アクセスの負荷に耐えられることを確認したいとき 6 | - オンラインで複数推論モデルのビジネス価値を計測するとき 7 | - 新推論モデルが現行の推論モデルより悪い結果を出さないことを確認したいとき 8 | 9 | ## Architecture 10 | オンラインABテストパターンは複数の推論モデルおよび推論サーバを本番データで試験する手法です。オンラインABテストパターンでは複数の推論サーバを稼働させ、現行サーバに過半数のアクセスを振り分けつつ、新サーバに徐々にアクセスを流していきます。アクセス量の調整はプロキシサーバで行います。プロキシサーバはリクエストを一意に特定するIDと入力データ、推論結果を分析用DWHに格納します。ワークフローによっては推論結果を受けたクライアントの行動ログも収集し、新旧モデルの比較に利用します。アクセス振り分けのルールは目的次第です。新モデルによるエンドユーザの行動分析を行いたい場合、同一ユーザは同一推論モデルに流すほうが良いでしょう。違反検知等、推論結果を溜めるものであれば、ランダムに振り分けるか、両方にアクセスさせるという戦略も考えられます。
11 | 新推論モデルの推論結果やスピード、可用性に問題がある場合、現行サーバにアクセスを戻し、新推論モデルを停止します。新推論モデルの有効性を計測する期間は検討が必要です。季節性のあるサービスであれば長期的に計測する必要がありますし、毎日使うサービスであれば一週間程度で結果が出るでしょう。他方で新推論モデルのリリースから即座に結果がわかる場合(株価等、結果が順次判明する場合)もあります。新旧モデルの継続、停止は推論結果と影響を見て判断する必要があります。
12 | オンラインABテストパターンは新モデルが本番システムに接続し、推論結果をクライアントに返却します。ビジネスや周辺システムへ影響あるテストパターンになり、注意が必要です。 13 | 14 | 15 | ## Diagram 16 | ![diagram](diagram.png) 17 | 18 | 19 | ## Pros 20 | - 新モデルの推論結果やスピード、可用性を本番サービスで確認することができる。 21 | - 複数モデルの推論結果を収集し分析することが可能。 22 | 23 | ## Cons 24 | - 新モデルが負のビジネス影響を及ぼす場合がある。 25 | - 新推論サーバのためのコストが発生。 26 | 27 | ## Needs consideration 28 | - 新旧モデルへのアクセス量の割り振り方法および量 29 | - 収集するログおよび新旧モデルの評価方法、試験期間、停止・継続の判断基準 30 | 31 | ## Sample 32 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter6_operation_management/online_ab_pattern -------------------------------------------------------------------------------- /QA-patterns/Online-ab-test-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Online AB test pattern 2 | 3 | ## Usecase 4 | - 새로운 예측 모델이 운영 환경 데이터에서 문제없이 예측할 수 있는지 확인하고 싶은 경우. 5 | - 새로운 예측 서버가 운영 환경 액세스 부하를 견딜 수 있는지 확인하고 싶은 경우. 6 | - 온라인으로 여러 예측 모델의 비즈니스 가치를 측정하고 싶은 경우. 7 | - 새로운 예측 모델이 현재의 예측 모델보다 나쁜 결과를 내지 않는 것을 확인하고 싶은 경우. 8 | 9 | ## Architecture 10 | Online AB test pattern은 여러 예측 모델 및 예측 서버를 프러덕션 데이터에서 시험하는 방법입니다. 이 패턴은 여러 예측 서버를 병렬로 배포하고, 이들 간에 부하를 분산합니다. 현재 모델에 더 높은 부하를 유지하고 새로운 모델에 대한 액세스를 점진적으로 늘립니다. 로드 밸런싱은 프록시 서버에서 관리됩니다. 프록시 서버는 ID와 함께 요청 데이터 및 예측을 데이터 웨어하우스에 저장합니다. 새 모델의 영향을 비교하려면 클라이언트 이벤트 로그를 확인해야 할 수 있습니다. 목표에 따라 로드 밸런싱 규칙을 고려할 수 있습니다. 목표가 사용자 활동을 비교하는 것이라면 사용자를 동일한 모델에 할당하는 것이 좋습니다. 목표가 예측 결과를 기록하는 것이라면 무작위로 균형을 맞추거나 모든 예측에 요청을 보낼 수 있습니다.
11 | 12 | 새로운 예측 모델의 예측 결과와 대기 시간, 가용성에 문제가 있는 경우 현재 서버에 액세스를 리턴시키고 새로운 예측 모델을 중지합니다. 새로운 모델의 유효성을 측정하는 기간은 검토가 필요합니다. 서비스가 시즈널리티가 존재하면 모델을 오래 테스트해야 하고, 만약 서비스가 매일 비슷하게 사용된다면 일주일 정도에 결과가 나올 것입니다. 한편 새로운 모델을 출시하자마자 즉시 결과를 아는 경우도 있습니다(주가 등 결과가 순차적으로 판명되는 경우). 새 모델이 현재 모델을 대체할 수 있는지는 예측 결과와 영향을 보고 결정하는 것이 중요합니다.
13 | 14 | Online AB test pattern은 새로운 모델을 프러덕션경시스템에 연결하고 예측 결과를 클라이언트에 반환합니다. 비즈니스 또는 사용자 경험에 영향을 미친다는 점을 유의하는 것이 중요합니다. 15 | 16 | 17 | ## Diagram 18 | ![diagram](diagram.png) 19 | 20 | 21 | ## Pros 22 | - 새로운 모델의 예측 결과와 속도, 가용성을 프러덕션 서비스에서 확인할 수 있습니다. 23 | - 여러 모델의 예측 결과를 수집하고 분석할 수 있습니다. 24 | 25 | ## Cons 26 | - 새로운 모델이 부정적인 비즈니스 영향을 미칠 수 있습니다. 27 | - 새로운 예측 서버에 대한 추가 비용이 발생합니다. 28 | 29 | ## Needs consideration 30 | - 부하 분산 정책. 31 | - 새 모델을 사용할지 말지에 대한 평가 방식 및 판단 기준이 필요합니다. 32 | 33 | ## Sample 34 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter6_operation_management/online_ab_pattern 35 | -------------------------------------------------------------------------------- /QA-patterns/Online-ab-test-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/QA-patterns/Online-ab-test-pattern/diagram.png -------------------------------------------------------------------------------- /QA-patterns/README.md: -------------------------------------------------------------------------------- 1 | # QA patterns 2 | 3 | - [Shadow AB-testing pattern](./Shadow-ab-test-pattern/design_en.md) 4 | 5 | 6 | - [Online AB-testing pattern](./Online-ab-test-pattern/design_en.md) 7 | 8 | 9 | - [Loading test pattern](./Loading-test-pattern/design_en.md) 10 | 11 | - [Antipatterns](./Anti-patterns/README.md) 12 | 13 | - [Offline-only pattern](./Anti-patterns/Offline-only-pattern/design_en.md) -------------------------------------------------------------------------------- /QA-patterns/README_ja.md: -------------------------------------------------------------------------------- 1 | # QA patterns 2 | 3 | - [Shadow AB-testing pattern](./Shadow-ab-test-pattern/design_ja.md) 4 | 5 | 6 | - [Online AB-testing pattern](./Online-ab-test-pattern/design_ja.md) 7 | 8 | 9 | - [Loading test pattern](./Loading-test-pattern/design_ja.md) 10 | 11 | - [Antipatterns](./Anti-patterns/README_ja.md) 12 | 13 | - [Offline-only pattern](./Anti-patterns/Offline-only-pattern/design_ja.md) -------------------------------------------------------------------------------- /QA-patterns/README_ko.md: -------------------------------------------------------------------------------- 1 | # QA patterns 2 | 3 | - [Shadow AB-testing pattern](./Shadow-ab-test-pattern/design_ko.md) 4 | 5 | 6 | - [Online AB-testing pattern](./Online-ab-test-pattern/design_ko.md) 7 | 8 | 9 | - [Loading test pattern](./Loading-test-pattern/design_ko.md) 10 | 11 | - [Antipatterns](./Anti-patterns/README_ko.md) 12 | 13 | - [Offline-only pattern](./Anti-patterns/Offline-only-pattern/design_ko.md) -------------------------------------------------------------------------------- /QA-patterns/Shadow-ab-test-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Shadow AB test pattern 2 | 3 | ## Usecase 4 | - To confirm the a new prediction model works with the production data. 5 | - To verify a new prediction server can load the production access. 6 | 7 | ## Architecture 8 | The shadow AB test pattern is an architecture to verity multiple prediction models with the production data and load. In this pattern, you will deploy multiple prediction servers, with sending requests to all the services, while the response will be only sent from the current model. The predictions of other models will not be sent to the client. The proxy server will store all the prediction results with profile to DWH. You will record prediction as well as latency without affecting client experience, to verify quality of the new model service.
9 | If there happens to have any issue with the new model, the prediction service will not be productionalized, and eliminated from the AB testing. You need to consider the term of testing. If the service has seasonal effect, you may need to run longer term, while if the service is used everyday in similar manner, the performance can be concluded in a few week. There may be a chance that you may find the result in shorter term. It is important to decide go or no go based on the effect of the new model replacing the current one.
10 | In contrast to the online AB test pattern, the shadow AB test pattern will allow you to compare the current and new models with less risk. On the other hand, since the pattern will not send the new model prediction to the client, it is difficult to measure its business impact. It is recommended to apply the online AB testing pattern once the model goes through the shadow AB test pattern. 11 | 12 | 13 | ## Diagram 14 | ![diagram](diagram.png) 15 | 16 | 17 | ## Pros 18 | - You can verity the new model performance without affecting the production service. 19 | - It is possible to record multiple predictions. 20 | 21 | ## Cons 22 | - Additional cost. 23 | 24 | ## Needs consideration 25 | - Evaluation and decision policy of go or no go for the new model. 26 | 27 | ## Sample 28 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter6_operation_management/shadow_ab_pattern -------------------------------------------------------------------------------- /QA-patterns/Shadow-ab-test-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Shadow AB test pattern 2 | 3 | ## Usecase 4 | - 新推論モデルが本番データで問題なく推論できることを確認したいとき 5 | - 新推論サーバが本番アクセスの負荷に耐えられることを確認したいとき 6 | 7 | ## Architecture 8 | シャドウABテストパターンは複数の推論モデルおよび推論サーバを本番データで試験する手法です。シャドウABテストパターンでは複数の推論サーバを稼働させ、プロキシサーバは全推論モデルへリクエストを送信しますが、クライアントへ推論結果を返すのは現行モデルのみです。そのため新モデルの推論結果はクライアントへ送信しません。プロキシサーバは両方の推論結果を分析用DWHに格納します。シャドウABテストパターンではクライアントへ影響なく新モデルの推論結果やスピードを計測し、本番導入の可否を判断します。
9 | 新推論モデルの推論結果やスピード、可用性に問題がある場合、新推論モデルを停止します。新推論モデルの有効性を計測する期間は検討が必要です。季節性のあるサービスであれば長期的に計測する必要がありますし、毎日使うサービスであれば一週間程度で結果が出るでしょう。他方で新推論モデルのリリースから即座に結果がわかる場合(株価等、結果が順次判明する場合)もあります。新旧モデルの継続、停止は推論結果と影響を見て判断する必要があります。
10 | シャドウABテストパターンはオンラインABテストパターンと違い、本番へのリスクなく新推論モデルを試験することが可能です。他方で、新モデルの推論結果はクライアントへ返却されないため、最終的なビジネス価値を測ることが難しくなります。シャドウABテストパターンで推論モデルが問題なく稼働することを確認したら、オンラインABテストパターンでビジネス価値を計測することを推奨します。 11 | 12 | 13 | ## Diagram 14 | ![diagram](diagram.png) 15 | 16 | 17 | ## Pros 18 | - 新モデルの推論結果やスピード、可用性を本番サービスで確認することができる。 19 | - 複数モデルの推論結果を収集し分析することが可能。 20 | 21 | ## Cons 22 | - 新推論サーバのためのコストが発生。 23 | 24 | ## Needs consideration 25 | - 収集するログおよび新旧モデルの評価方法、試験期間、停止・継続の判断基準 26 | 27 | ## Sample 28 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter6_operation_management/shadow_ab_pattern -------------------------------------------------------------------------------- /QA-patterns/Shadow-ab-test-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Shadow AB test pattern 2 | 3 | ## Usecase 4 | - 새로운 예측 모델이 운영 환경 데이터에서 잘 동작하는지 확인하고 싶은 경우. 5 | - 새로운 예측 서버가 운영 환경 부하를 견딜 수 있는지 확인하고 싶은 경우. 6 | 7 | 8 | ## Architecture 9 | Shadow AB test pattern은 여러 예측 모델 및 서버를 운영 환경 데이터를 사용해 검증하는 아키텍처입니다. 이 패턴은 여러 예측 서버를 배포하고 모든 서비스에 예측 요청을 전송하며 예측 응답은 현재 모델에만 보냅니다. 따라서 새로운 모델의 예측은 클라이언트에 전송되지 않습니다. 프록시 서버는 예측 모델의 프로필과 모든 예측 결과를 데이터 웨어하우스에 저장합니다. 새로운 모델의 품질을 확인하기 위해 클라이언트 환경에 영향을 주지 않고 예측 결과와 대기 시간을 측정하고 실전 도입 여부를 판단합니다.
10 | 11 | 새로운 모델에 문제가 발생할 경우 예측 서비스는 운영 환경에 배포하지 않고, AB 테스트에서 제거됩니다. 새로운 모델의 유효성을 측정하는 기간은 검토가 필요합니다. 서비스가 시즈널리티가 존재하면 모델을 오래 테스트해야 하고, 만약 서비스가 매일 비슷하게 사용된다면 일주일 정도에 결과가 나올 것입니다. 한편 새로운 모델의 출시하자마자 즉시 결과를 아는 경우도 있습니다(주가 등 결과가 순차적으로 판명되는 경우). 새 모델이 현재 모델을 대체할 수 있는지는 예측 결과와 영향을 보고 결정하는 것이 중요합니다.
12 | 13 | Online AB test pattern과 달리, Shadow AB test pattern을 사용하면 적은 위험 부담으로 현재 모델과 새로운 모델을 비교할 수 있습니다. 반면 새로운 모델의 예측을 클라이언트에 반환하지 않기 때문에 비즈니스 영향을 측정하기 어렵습니다. Shadow AB test pattern에서 예측 모델이 문제없이 작동하는 것을 확인한 후, Online AB test pattern에서 비즈니스 가치를 측정하는 것을 추천합니다. 14 | 15 | 16 | 17 | ## Diagram 18 | ![diagram](diagram.png) 19 | 20 | 21 | ## Pros 22 | - 운영 환경에 영향을 주지 않고 새로운 모델 성능을 확인할 수 있습니다. 23 | - 여러 모델의 예측 결과를 수집하고 분석할 수 있습니다. 24 | 25 | ## Cons 26 | - 새로운 예측 서버에 대한 추가 비용이 발생합니다. 27 | 28 | ## Needs consideration 29 | - 새 모델을 사용할지 말지에 대한 평가 방식 및 판단 기준이 필요합니다. 30 | 31 | ## Sample 32 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter6_operation_management/shadow_ab_pattern 33 | -------------------------------------------------------------------------------- /QA-patterns/Shadow-ab-test-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/QA-patterns/Shadow-ab-test-pattern/diagram.png -------------------------------------------------------------------------------- /Serving-patterns/Anti-patterns/All-in-one-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # All-in-one pattern 2 | 3 | ## Case 4 | - When you are running multiple inference models in one server or one server group. 5 | 6 | ## Situation 7 | While there are many usecases you need to deploy multiple inference models for one product, it is recommended not to run them in one same server or a same server group. Running all the models in a monorithic environment may barely reduce server cost, though it will probably increase operational cost with difficulty of software development, troubleshooting and update.
8 | A disadvantage for its model development in this situation is that you will get limitation in your library selection. Libraries and algorithms for machine learning have been changing rapidly. Developing a model aligned with another model development will become limitation in algorithm choice, that you may not be your best choice.
9 | Once you get an incident in a monorithic architecture, you may need to trace all logs to find its root cause. Isolating fault in a system becomes difficult, as well as troubleshooting a machine learning model, such that prediction is invalid, requires tracing multiple logics, which will be increase in time to repair.
10 | Updating system and model requires comparably long time as well. Depending on how you install your model, [model in image patter](../../../Operation-patterns/Model-in-image-pattern/design_en.md) or [model load pattern](../../../Operation-patterns/Model-load-pattern/design_en.md), an update in the system will require an unnecessary update in a model. Frequency of system update and model update may not be synchronized, though those will be triggered simultaneously on a monorithic system, with increase in operational cost.
11 | It is recommended to deploy in microservice architecture of one model per one server on running multiple models. 12 | 13 | ## Diagram 14 | ![diagram](diagram.png) 15 | 16 | 17 | ## Pros 18 | - Barely reasonable cost. 19 | 20 | ## Cons 21 | - Increase in dev and ops cost. 22 | 23 | ## Work around 24 | - Develop in a single responsibility for a server and a model, in microservice. 25 | 26 | 27 | ## Related design pattern 28 | - [Prep-pred pattern](./../../Prep-pred-pattern/design_en.md) 29 | - [Microservice vertical pattern](./../../Microservice-vertical-pattern/design_en.md) 30 | - [Microservice horizontal pattern](./../../Microservice-horizontal-pattern/design_en.md) -------------------------------------------------------------------------------- /Serving-patterns/Anti-patterns/All-in-one-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # All-in-one pattern 2 | 3 | ## Case 4 | - 複数の推論モデルを稼働させるシステムで、全てのモデルが同一のサーバで稼働している状態。 5 | 6 | ## Situation 7 | 1つの目的のために複数の推論モデルを稼働させたいユースケースは存在しますが、全推論モデルを同一サーバで稼働させることは避けたほうが良いでしょう。全推論器を同一環境でモノリシックに稼働させる場合、サーバコストは多少安価に済むかもしれませんが、モデル開発や障害切り分け、更新が難しくなり、人件費が増大するでしょう。
8 | モデル開発のデメリットは環境選択の自由度が制限されることです。機械学習のライブラリやアルゴリズムは日進月歩で更新されています。他のモデルと足並みを揃えて環境構築することは、使えるロジックの制限となり、最適な選択ができなくなる可能性があります。
9 | モノリシックな環境で障害が発生した場合、障害箇所を全てのログから検索し特定する必要があります。システム的な障害切り分けは困難になりますが、同様に機械学習モデルとしての障害(正常な推論が成されていない状況)も、同一環境で全てのロジックをトレースすることになり、複雑性と障害対応時間が増すでしょう。
10 | システムやモデルの更新も同様に複雑かつ時間を要するものになります。モデルの展開方法([モデル・イン・イメージ・パターン](./../../../Operation-patterns/Model-in-image-pattern/design_ja.md)か[モデル・ロード・パターン](./../../../Operation-patterns/Model-load-pattern/design_ja.md)か)にも依りますが、システム更新と同時にモデル更新が発生し、整合性を検証する必要があります。システムの更新頻度とモデルの更新頻度は一致しないことが多いですが、モノリシックな構成だと両方を同時に更新するため、作業コストが増大します。
11 | 複数のモデルを稼働させる場合、特別の理由がない限りは1モデル1推論器のマイクロサービスにして運用することを推奨します。 12 | 13 | ## Diagram 14 | ![diagram](diagram.png) 15 | 16 | 17 | ## Pros 18 | - サーバコストは多少安価。 19 | 20 | ## Cons 21 | - 開発、運用コストが増大。 22 | 23 | ## Work around 24 | - 単一責任の原則に則り、マイクロサービスとして開発し、運用する。 25 | 26 | ## Related design pattern 27 | - [Prep-pred pattern](./../../Prep-pred-pattern/design_ja.md) 28 | - [Microservice vertical pattern](./../../Microservice-vertical-pattern/design_ja.md) 29 | - [Microservice horizontal pattern](./../../Microservice-horizontal-pattern/design_ja.md) -------------------------------------------------------------------------------- /Serving-patterns/Anti-patterns/All-in-one-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # All-in-one pattern 2 | 3 | ## Case 4 | - 하나의 서버 또는 하나의 서버 그룹에서 여러 예측 모델을 실행하는 경우. 5 | 6 | ## Situation 7 | 하나의 제품에서 여러 예측 모델을 배포하고 싶은 경우가 있지만, 하나의 서버 또는 하나의 서버 그룹에서 여러 예측 모델을 실행하는 것은 추천하지 않습니다. 모든 모델을 단일 환경에서 실행하면 서버 비용을 줄일 수 있지만, 소프트웨어 개발, 트러블슈팅, 업데이트의 어려움으로 운영 비용이 증가할 수 있습니다.
8 | 9 | 이 상황에서 모델 개발을 할 경우 라이브러리(환경) 선택에 제한이 생깁니다. 머신러닝을 위한 라이브러리와 알고리즘은 빠르게 변하고 있습니다. 다른 모델에 맞춰 모델을 개발하면 알고리즘 선택이 제한될 것이고, 아마 제일 좋은 알고리즘을 선택할 수 없을 수 있습니다.
10 | 11 | 단일 아키텍처에서 장애가 발생하면, 근본 원인을 찾기 위해 모든 로그를 확인해야 할 수 있습니다. 시스템에서 결함을 분리하는 것이 어려워지고, 머신러닝 모델의 장애(정상적인 예측이 이루어지지 않은 상황)도 모든 로직을 확인해야 해서 복잡성과 문제를 해결하는 시간이 늘어납니다.
12 | 13 | 14 | 시스템과 모델의 업데이트도 마찬가지로 복잡하고 오랜 시간이 필요합니다. 모델을 설치하는 방법에 따라, [Model in image pattern](../../../Operation-patterns/Model-in-image-pattern/design_ko.md) 또는 [Model load pattern](../../../Operation-patterns/Model-load-pattern/design_ko.md)를 사용할 수 있습니다. 이런 시스템의 업데이트는 모델 입장에선 불필요한 업데이트일 수 있습니다. 시스템 업데이트 및 모델 업데이트의 빈도는 일치하지 않는 경우가 많지만, 단일 시스템이라면 양쪽을 동시에 갱신하기 때문에 운영 비용이 증가합니다.
15 | 16 | 여러 모델을 운영하는 경우, 특별한 이유가 없다면 서버당 한 모델의 마이크로 서비스 아키텍처로 배포하는 것을 추천합니다. 17 | 18 | ## Diagram 19 | ![diagram](diagram.png) 20 | 21 | 22 | ## Pros 23 | - 거의 합리적인 비용. 24 | 25 | ## Cons 26 | - 개발과 운영 비용이 증가합니다. 27 | 28 | ## Work around 29 | - 마이크로 서비스에서 서버와 모델을 단일 책임으로 개발합니다. 30 | 31 | 32 | ## Related design pattern 33 | - [Prep-pred pattern](./../../Prep-pred-pattern/design_ko.md) 34 | - [Microservice vertical pattern](./../../Microservice-vertical-pattern/design_ko.md) 35 | - [Microservice horizontal pattern](./../../Microservice-horizontal-pattern/design_ko.md) 36 | -------------------------------------------------------------------------------- /Serving-patterns/Anti-patterns/All-in-one-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Anti-patterns/All-in-one-pattern/diagram.png -------------------------------------------------------------------------------- /Serving-patterns/Anti-patterns/Online-bigsize-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Online bigsize pattern 2 | 3 | ## Case 4 | - Condition when you deploy a bigsize model that takes long for an inference in an online service or system that require realtime response. 5 | - Condition where average latency of predictions does not meet required performance. 6 | - Condition where product of number of prediction and average latency is longer than expected completion in batch system. 7 | 8 | ## Situation 9 | In any service, including web and batch, there is a requirement or expectation for time of completion for one task. For instance in a web service, the requirement might a mean time to respond for each request. For a batch system, completing processing of a hundred million records in 6 hours, midnight, would be a requirement. In any business and system, time is always limited and expensive that you cannot take everlasting time for one task. A standard and useful unit for cumulating time taken for task is average seconds taken for a prediction in machine learning system, and you have to design a model and prediction system to meet the requirement. Especially in a case of using a complex and gigantic deep learning model that may be time-consuming, you have to optimize somehow, or it will be impossible in web realtime services. You may try scale up or out to balance amount of process per server, though this can only be applied if unit inference responding time meets requirement. You may also try using an inference GPU, which may be costful than CPU. It is also a challenge, and might be the best choice, to make a simple model to meet the performance and latency.
10 | There is no best answer for taking a balance of model evaluation and speed tradeoff. It is important to define service level of the evaluation and speed according to business and system needs. 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - Evaluation may be better on a big and complex model. 18 | - It is fun making a complex model. 19 | 20 | ## Cons 21 | - Need to take balance of speed, cost and accuracy. 22 | - It is also fun making a simple and reasonable model. 23 | 24 | ## Work around 25 | - Define latency or speed required for business use or system to evaluate the model quality, not only of accuracy. 26 | - Try using GPU, or scale out, if it is cost effective. 27 | 28 | ## Related design pattern 29 | - [Prediction cache pattern](./../../Prediction-cache-pattern/design_en.md) 30 | - [Data cache pattern](./../../Data-cache-pattern/design_en.md) 31 | - [Loading test pattern](./../../../QA-patterns/Loading-test-pattern/design_en.md) 32 | - [Prediction log pattern](./../../../Operation-patterns/Prediction-log-pattern/design_en.md) 33 | - [Prediction monitoring pattern](./../../../Operation-patterns/Prediction-monitoring-pattern/design_en.md) -------------------------------------------------------------------------------- /Serving-patterns/Anti-patterns/Online-bigsize-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Online bigsize pattern 2 | 3 | ## Case 4 | - オンラインのサービスやリアルタイムな処理が必要なシステムで推論に時間を要するモデルを配備している状態。 5 | - サービスの求めるレイテンシーと機械学習モデルが実現可能な推論時間が一致していない状態。 6 | - 完了時間の決まっているバッチ処理で、推論数×推論時間が完了時間に間に合わない状態。 7 | 8 | ## Situation 9 | Webサービスにせよバッチ処理にせよ、ひとつの処理を完了するのに求められる所要時間の要件があります。Webサービスであれば1リクエストに対して1秒以内にレスポンスするという要件になります。バッチ処理であれば夜間6時間で1億件のレコードを完了する、というものになります。いかなるビジネスやシステムにおいても、時間は有限かつ貴重であるため、1回の処理に長時間を費やすことはできません。機械学習の推論器を組み込んで稼働させる場合、推論器の所要時間がシステムの要件を満たすように開発する必要があります。特に複雑で頂戴なディープラーニングのモデルは計算量が膨大になるため、Webサービスでオンラインで稼働させることは難しくなるでしょう。スケールアウトやスケールアップで1サーバの処理量を減らして高速化することも可能ですが、1推論時間が要件を満たすことが条件になります。推論の処理時間を短縮するために推論用GPUを使うことも可能ですが、通常のCPUよりコストが割高になります。シンプルなモデルで推論速度を向上することも可能ですが、Accuracy等の評価値が複雑なモデルよりも低くなる可能性もあります。
10 | モデルの評価vsスピードのバランスに正解はありませんが、どういう推論とスピードであればビジネスやシステム要件を満たすのか、モデル開発と共同してサービスレベルを定めることが肝要です。 11 | 12 | 13 | ## Diagram 14 | ![diagram](diagram.png) 15 | 16 | 17 | ## Pros 18 | - 長大で複雑なモデルのほうが機械学習の評価値は良くなることが多い。 19 | - 複雑なモデルを作るのは楽しい。 20 | 21 | ## Cons 22 | - スピードとコストが犠牲になる。 23 | - シンプルでリーズナブルなモデルを作るのも楽しい。 24 | 25 | ## Work around 26 | - 推論機の評価値と同時に、ビジネス的またはシステム的に求められる処理時間やスピードを定義し、それら要件を満たすモデル開発を行う。 27 | - コストが許すのであればスケールアウトやスケールアップ、GPUの利用等を検討する。 28 | 29 | ## Related design pattern 30 | - [Prediction cache pattern](./../../Prediction-cache-pattern/design_ja.md) 31 | - [Data cache pattern](./../../Data-cache-pattern/design_ja.md) 32 | - [Loading test pattern](./../../../QA-patterns/Loading-test-pattern/design_ja.md) 33 | - [Prediction log pattern](./../../../Operation-patterns/Prediction-log-pattern/design_ja.md) 34 | - [Prediction monitoring pattern](./../../../Operation-patterns/Prediction-monitoring-pattern/design_ja.md) -------------------------------------------------------------------------------- /Serving-patterns/Anti-patterns/Online-bigsize-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Online bigsize pattern 2 | 3 | ## Case 4 | - 실시간 대응이 필요한 온라인 서비스의 경우 또는 시스템에 예측에 오랜 시간이 걸리는 큰 모델을 배치하는 경우 5 | - 예측의 평균 지연 시간이 요구되는 성능을 충족하지 못하는 경우 6 | - 배치 시스템에서 예측 횟수 또는 평균 지연 시간이 예상되는 완료 시간보다 긴 경우 7 | 8 | ## Situation 9 | 웹 서비스와 배치 시스템을 포함한 모든 서비스에는 완료 시간에 대한 요구 사항이 있습니다. 예를 들면, 웹 서비스에서는 모든 요청의 평균 응답 시간이 1초 이하가 되어야 한다는 것이 있습니다. 배치 시스템에서는 1억 개의 요청을 저녁 6시간 내에 처리해야 한다는 것이 요구 사항이 될 수 있습니다. 10 | 어떤 비즈니스 또는 시스템이든지 간에, 시간은 한정되어 있는 귀중한 자원이기 때문에 1회 처리에 무한정의 시간을 소비할 수 없습니다. 작업의 소요되는 시간을 측정할 수 있는 유용한 단위는 머신러닝 시스템이 예측에 소비하는 평균 초로, 이 단위를 기준으로 요구 사항에 충족할 수 있게 모델과 예측 시스템을 설계해야 합니다. 특히 시간이 많이 걸릴 수 있는 복잡하고 거대한 딥러닝 모델을 사용하는 경우에는 어떻게든 최적화해야 합니다. 최악의 경우, 웹 실시간 서비스로는 사용이 불가능할 수 있습니다. 11 | 단위 예측 응답 시간이 요구 사항을 충족하는 경우에만 적용할 수 있지만, 스케일 업 또는 스케일 아웃을 시도해 서버당 동작하는 프로세스 양의 균형을 맞출 수 있습니다. 또는 CPU보다 비용이 많이 들 수도 있지만, 예측 특화형 GPU를 사용할 수도 있습니다. 성능과 지연 시간을 충족시키기 위해 간단한 모델을 만드는 것도 최선의 선택일 수 있습니다.
12 | 모델의 성능과 속도의 균형에 정답은 없습니다. 따라서 비즈니스 및 시스템 요구사항에 따라 성능 및 속도의 서비스 수준을 정의하는 것이 중요합니다. 13 | 14 | ## Diagram 15 | ![diagram](diagram.png) 16 | 17 | 18 | ## Pros 19 | - 크고 복잡한 모델이 성능이 더 좋은 경우가 많습니다. 20 | - 복잡한 모델을 만드는 것은 재미있습니다. 21 | 22 | ## Cons 23 | - 속도와 비용, 정확성 간의 균형을 잡을 필요가 있습니다. 24 | - 간단하고 재사용 가능한 모델을 만드는 것도 재미있습니다. 25 | 26 | ## Work around 27 | - 모델의 정확성 뿐만 아니라, 비즈니스적 또는 시스템적으로 요구되는 응답 시간이나 속도를 충족하는 모델을 개발합니다. 28 | - 만약 비용면에서 허락한다면, GPU를 사용하거나 스케일 아웃 하는 방법도 고려해보세요. 29 | 30 | ## Related design pattern 31 | - [Prediction cache pattern](./../../Prediction-cache-pattern/design_ko.md) 32 | - [Data cache pattern](./../../Data-cache-pattern/design_ko.md) 33 | - [Loading test pattern](./../../../QA-patterns/Loading-test-pattern/design_ko.md) 34 | - [Prediction log pattern](./../../../Operation-patterns/Prediction-log-pattern/design_ko.md) 35 | - [Prediction monitoring pattern](./../../../Operation-patterns/Prediction-monitoring-pattern/design_ko.md) 36 | -------------------------------------------------------------------------------- /Serving-patterns/Anti-patterns/Online-bigsize-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Anti-patterns/Online-bigsize-pattern/diagram.png -------------------------------------------------------------------------------- /Serving-patterns/Anti-patterns/README.md: -------------------------------------------------------------------------------- 1 | # Serving Antipatterns 2 | 3 | - [Online bigsize pattern](./Online-bigsize-pattern/design_en.md) 4 | 5 | - [All-in-one pattern](./All-in-one-pattern/design_en.md) -------------------------------------------------------------------------------- /Serving-patterns/Anti-patterns/README_ja.md: -------------------------------------------------------------------------------- 1 | # Serving Antipatterns 2 | 3 | - [Online bigsize pattern](./Online-bigsize-pattern/design_ja.md) 4 | 5 | - [All-in-one pattern](./All-in-one-pattern/design_ja.md) -------------------------------------------------------------------------------- /Serving-patterns/Anti-patterns/README_ko.md: -------------------------------------------------------------------------------- 1 | # Serving Antipatterns 2 | 3 | - [Online bigsize pattern](./Online-bigsize-pattern/design_ko.md) 4 | 5 | - [All-in-one pattern](./All-in-one-pattern/design_ko.md) 6 | -------------------------------------------------------------------------------- /Serving-patterns/Asynchronous-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Asynchronous pattern 2 | 3 | ## Usecase 4 | - When the immediate process does not depend on the prediction. 5 | - To separate the client which is making the prediction request and the destination where response is expected. 6 | 7 | ## Architecture 8 | The asynchronous pattern realizes separation of a prediction request and prediction retrieval with placing queue or cache in between the client and predictor. It will allow the client to not to wait for the inference latency. In order for the client to get the prediction, you have to add poling to pull the result from the queue. If you want the prediction result to be retrieved by a resource other than the client, like `Diagram2`, it can proceed to the next step without waiting for the prediction latency.
9 | In addition, both in case of `Diagram1` and `Diagram2`, you can make the prediction server to push the result to the other component, while you have to carefully consider its usecase for the system and workflow becomes quite complex. 10 | 11 | ## Diagram 12 | ### Diagram1 13 | ![diagram1](diagram1.png) 14 | 15 | ### Diagram2 16 | ![diagram2](diagram2.png) 17 | 18 | ## Pros 19 | - You can separate client and prediction. 20 | - The client does not have to wait for the prediction latency. 21 | 22 | ## Cons 23 | - Requires queue, cache or similar kind of proxy. 24 | - Not fit to real-time usecase. 25 | 26 | ## Needs consideration 27 | - How to trigger prediction: 28 | - Queue: prediction will be FIFO 29 | - Cache: depends on existence of cache 30 | - PubSub: predictor's subscription to run prediction 31 | - Needs consideration for prediction error: 32 | - If you need to retry, consider triggering retry in the prediction server or return to queue. 33 | - If the error is caused by data or programmatical issue, there may be a chance that the request keeps retrying until you manually disposes the request. 34 | - Since the pattern does not support ordered predition, you have to consider the workflow if you need concrete order for input or event in the usecase. 35 | 36 | ## Sample 37 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/asynchronous_pattern -------------------------------------------------------------------------------- /Serving-patterns/Asynchronous-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Asynchronous pattern 2 | 3 | ## Usecase 4 | - 直後の動作が推論結果に依存しないワークフローのとき 5 | - 呼び出し元のクライアントと推論結果の出力先を分離するとき 6 | 7 | ## Architecture 8 | 非同期パターンはリクエストと推論の中間にキューやキャッシュを配置することで、推論リクエストと推論結果の取得を非同期にします。リクエストと推論を切り離すことにより、クライアントのワークフローで推論時間を待つ必要がなくなります。クライアントで推論結果を得るには、クライアント側でキューをポーリングしてPullする必要があります。`Diagram2`のように推論のリクエスト元と出力先が違う場合、非同期パターンにすることによってクライアントは推論を待たずに処理を続行することが可能になります。
9 | 加えて、`Diagram1`、`Diagram2`のいずれにおいても、推論結果は推論器からクライアントや出力先に直接Pushすることも可能ですが、推論器側が推論結果を返却するためのコネクションが必要になりシステムが複雑になるため、検討が必要です。 10 | 11 | ## Diagram 12 | ### Diagram1 13 | ![diagram1](diagram1.png) 14 | 15 | ### Diagram2 16 | ![diagram2](diagram2.png) 17 | 18 | ## Pros 19 | - クライアントと推論を切り離すことが可能。 20 | - 推論の待機時間が長い場合でも、クライアントに悪影響が出ることが少ない。 21 | 22 | ## Cons 23 | - キューやキャッシュが必要になる。 24 | - リアルタイムな処理には向いていない。 25 | 26 | ## Needs consideration 27 | - 推論のトリガーを検討する必要がある。 28 | - キューで実装する場合:FIFOで推論。 29 | - キャッシュで実装する場合:キャッシュの有無で推論。 30 | - PubSubで実装する場合:サブスクライブによって推論。 31 | - 推論エラー時の対応方法を検討する必要がある。 32 | - リトライする場合、推論サーバ内でリトライするか、キュー/キャッシュに戻すか。 33 | - データやプログラムの誤りで推論エラーになる場合、そのリクエストを停止または破棄しない限り、リトライ↔エラーが続くことがある。 34 | - 厳密な順番は保証されないため、入力やイベントに対する推論順が重要なワークフローの場合は検討が必要。 35 | 36 | ## Sample 37 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/asynchronous_pattern -------------------------------------------------------------------------------- /Serving-patterns/Asynchronous-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Asynchronous pattern 2 | 3 | ## Usecase 4 | - 프로세스와 예측 사이에 의존성이 없는 경우. 5 | - 예측을 요청할 클라이언트와 응답할 목적지가 분리되어 있는 경우. 6 | 7 | ## Architecture 8 | Asynchronous pattern은 클라이언트와 예측 서버 사이에 대기열이나 캐시를 배치해 예측 요청과 예측 검색을 분리합니다. 이 패턴은 클라이언트가 예측 지연을 기다리지 않도록 합니다. 클라이언트가 예측을 얻으려면 큐에서 결과를 가져오기 위해 폴링을 추가해야 합니다. `Diagram2`와 같이 클라이언트 이외의 리소스에서 예측 결과를 검색하려는 경우 예측 대기 시간을 기다리지 않고 다음 단계로 진행할 수 있습니다.
9 | 또한, `Diagram1`과 `Diagram2`의 경우 예측 서버를 만들어 결과를 다른 구성 요소로 푸시하도록 만들 수 있지만, 시스템의 사용 사례를 신중하게 고려해야 하고 워크플로우가 매우 복잡해질 수 있습니다. 10 | 11 | 12 | ## Diagram 13 | ### Diagram1 14 | ![diagram1](diagram1.png) 15 | 16 | ### Diagram2 17 | ![diagram2](diagram2.png) 18 | 19 | ## Pros 20 | - 클라이언트와 예측을 분리할 수 있습니다. 21 | - 클라이언트가 예측 대기 시간을 기다릴 필요가 없습니다. 22 | 23 | ## Cons 24 | - 큐, 캐시 또는 유사한 종류의 프록시가 필요합니다. 25 | - 실시간 예측엔 적절하지 않습니다. 26 | 27 | ## Needs consideration 28 | - 예측을 실행할 방법: 29 | - Queue: FIFO(요청한 시간 순으로) 예측합니다. 30 | - Cache: 캐시의 존재 여부에 따라 다릅니다. 31 | - PubSub: 예측 서버가 구독할 경우 예측합니다. 32 | - 예측 오류에 대한 고려가 필요합니다: 33 | - 만약 재시도해야 하면, 예측 서버에서 재시도하거나 또는 큐로 돌아갑니다. 34 | - 만약 오류가 데이터 또는 프로그래밍 이슈로 발생했다면, 수동으로 요청을 처리할 때까지 요청이 계속 재시도될 가능성이 있습니다. 35 | - 이 패턴은 순서가 있는 예측을 지원하지 않기 때문에, 사용 사례에서 입력 또는 이벤트에 대한 구체적인 워크플로우를 고려해야 합니다. 36 | 37 | 38 | ## Sample 39 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/asynchronous_pattern -------------------------------------------------------------------------------- /Serving-patterns/Asynchronous-pattern/diagram1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Asynchronous-pattern/diagram1.png -------------------------------------------------------------------------------- /Serving-patterns/Asynchronous-pattern/diagram2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Asynchronous-pattern/diagram2.png -------------------------------------------------------------------------------- /Serving-patterns/Batch-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Batch pattern 2 | 3 | ## Usecase 4 | - If there is no need for real-time or near-real-time prediction. 5 | - If predictions are expected on a bulk of data. 6 | - If running predictions is schedulable; hourly, daily, weekly or monthly. 7 | 8 | ## Architecture 9 | If you don't have to run the predictions real-time, you may choose the batch pattern to run the predictions with the desired interval. You can schedule a batch prediction to a bulk of data regularly, such as daily, and store the results. Of course it can be hourly or monthly depending on the usecase. This pattern requires job management server to trigger the batch job. The job management server will launch the job as per your defined rules. The prediction server will be deployed along with the launch of the batch job. If you are using a cloud service or Kubernetes, starting and deleting the server based on the job will enable you to reduce your costs drastically as the server need not be up 24X7. 10 | 11 | ## Diagram 12 | ![diagram](diagram.png) 13 | 14 | ## Pros 15 | - You can manage server resources flexibly and in strict accordance with demand. 16 | - You may rerun the job in case of error. 17 | - There is no requirement for high availability in your server system 18 | 19 | ## Cons 20 | - You need a job management server. 21 | 22 | ## Needs consideration 23 | - You will need to consider the batch, or range, of dataset to predict in one job. If the dataset size for the defined interval is too large then it needs to be split and co-ordinated among several mini-jobs. 24 | - If you have a certain time limitation to get the prediction results, you need to consider batch job schedule and server resources. If it is nightly batch, it is often case that you have to finish the job by next morning. 25 | - Options to rerun the job in case of failure: 26 | - Retry all: rerun the whole prediction of a batch. Used when a prediction or data has dependency on others. 27 | - Partial retry: rerun on the failed dataset. Used when there is no dependency. 28 | - No retry: run prediction on the failed dataset on the next batch. Used when there is no strict time limitation. 29 | - If the batch timeframe is long, like once per month or once per year, it is suggested to monitor, or run temporarily, of the batch execution, for the model or system may be outdated. 30 | 31 | ## Sample 32 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/batch_pattern -------------------------------------------------------------------------------- /Serving-patterns/Batch-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Batch pattern 2 | 3 | ## Usecase 4 | - リアルタイムまたは準リアルタイムで推論する必要がないとき 5 | - 過去のデータにまとめて推論を実行したいとき 6 | - 夜間、毎時、毎月等、定期的にデータを推論したいとき 7 | 8 | ## Architecture 9 | 推論をリアルタイムに実行する必要がない場合、バッチ・パターンで定期的に推論を行うことが可能です。バッチ・パターンでは溜まったデータを夜間等、定期的に推論し、結果を保存することができます。もちろん夜間実行である必要はなく、ユースケースによって1時間毎・1ヶ月毎の実行も可能です。バッチ・パターンではバッチ・ジョブを起動するジョブ管理サーバが必要になります。ジョブ管理サーバは決められたルール(時間や他の条件)をトリガーにして推論のバッチ・ジョブを起動します。推論サーバはバッチ・ジョブの起動時のみに稼働します。基盤にクラウドやKubernetesを使用している場合、サーバの停止・起動をコントロールすることでコスト最適化も可能になります。 10 | 11 | ## Diagram 12 | ![diagram](diagram.png) 13 | 14 | ## Pros 15 | - サーバのリソース管理を柔軟に行うことが可能。 16 | - 何らかの理由で推論に失敗しても再度推論することが可能。 17 | 18 | ## Cons 19 | - ジョブ管理サーバが必要。 20 | 21 | ## Needs consideration 22 | - 一回のバッチ・ジョブでどの範囲のデータを推論するか、ジョブの起動条件が必要になる。 23 | - 推論結果を得るまでの期限が決められている場合、推論バッチ・ジョブの実行スケジュールや稼働する推論サーバ数を調整する必要がある。夜間バッチ等であれば、翌朝までに推論完了することが要件になる場合が多い。 24 | - バッチ・ジョブが失敗したときの方針が必要がある。 25 | - 全件リトライ:失敗した場合は再度推論バッチ・ジョブを実行し、全件を推論する。 26 | - 一部リトライ:失敗したデータのみ再度推論する。 27 | - 放置:失敗してもリトライを起動せず、次のバッチ・ジョブで推論する。 28 | - 毎月や毎年等、推論バッチ・ジョブを起動する時間が大きく離れる場合、機械学習モデルの有効性(Out-of-date)やサーバ自体の稼働可否をモニタリングする必要がある。 29 | 30 | ## Sample 31 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/batch_pattern 32 | -------------------------------------------------------------------------------- /Serving-patterns/Batch-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Batch pattern 2 | 3 | ## Usecase 4 | - 예측 결과를 실시간 또는 거의 실시간으로 얻을 필요가 없는 경우. 5 | - 대량의 데이터에 대해 예측을 하려는 경우. 6 | - 예측 실행이 스케줄링이 가능한 경우: 시간별, 일별, 주별, 월별 7 | 8 | ## Architecture 9 | 만약 예측을 실시간으로 실행할 필요가 없는 경우, 정기적으로 예측을 실행할 배치 패턴을 선택할 수 있습니다. 매일 대량의 데이터를 배치 예측을 스케줄링하고 결과를 저장할 수 있습니다. 물론 사용 사례에 따라 매시간 또는 매월이 될 수 있습니다. 이 패턴에는 작업 관리 서버가 배치 작업을 트리거해야 합니다. 서버는 정의된 규칙에 따라 작업을 시작합니다. 배치 작업 시작과 함께 예측 서버가 배포됩니다. 클라우드 서비스 또는 쿠버네티스를 사용하는 경우 작업을 기반으로 서버를 시작하고 삭제하면 비용을 절감할 수 있습니다. 10 | 11 | ## Diagram 12 | ![diagram](diagram.png) 13 | 14 | ## Pros 15 | - 서버 리소스를 유연하게 관리할 수 있습니다. 16 | - 오류가 발생할 경우 작업을 재실행할 수 있습니다. 17 | 18 | ## Cons 19 | - 작업 운영 서버가 필요합니다. 20 | 21 | ## Needs consideration 22 | - 한 작업에서 예측할 수 있는 데이터 집합의 양 또는 범위를 고려해야 합니다. 23 | - 예측 결과를 얻는데 시간 제한이 있는 경우, 배치 작업 스케줄 및 서버 리소스를 고려해야 합니다. 야간 배치 작업이면, 다음 날 아침까지 일을 끝내야 하는 경우가 많습니다. 24 | - 작업이 실패시 재실행하는 방법: 25 | - 모두 재시도: 배치의 전체 예측을 다시 실행합니다. 예측이나 데이터가 다른 것에 의존할 때 사용됩니다. 26 | - 부분 재시도: 실패한 데이터세트에서 다시 실행합니다. 의존성이 없을 때 사용됩니다. 27 | - 재시도 없음: 다음 배치에서 실패한 데이터 세트에 대해 예측을 실행합니다. 엄격한 시간 제한이 없을 때 사용됩니다. 28 | - 만약 배치 기간이 매월 1회 또는 1년에 1번 같이 긴 경우, 모델 또는 시스템이 오래되었을 수 있으므로 배치 실행을 모니터링하거나 임시로 실행하는 것이 좋습니다. 29 | 30 | ## Sample 31 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/batch_pattern -------------------------------------------------------------------------------- /Serving-patterns/Batch-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Batch-pattern/diagram.png -------------------------------------------------------------------------------- /Serving-patterns/Data-cache-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Data cache pattern 2 | 3 | ## Usecase 4 | - When you have prediction request for same and repeated data. 5 | - When the data can be identified with cache key. 6 | - When you want to accelerate data retrieval and processing. 7 | 8 | ## Architecture 9 | The data cache pattern will cache input data. If the input data is stored in database, storage or disk, you will be able to shorten overhead of acquiring data.
10 | The amount of data to cache may need to be considered with balance of cost and volume. The unit price for cache space tends to be higher with less size than storage or database, hence it is recommended to plan a policy to clear cache.
11 | If the prediction result changes with time, it requires to clear old cache to prevent responding with outdated prediction. If the service gets high load that the cache size increases rapidly, it is important to plan cache clear policy concretely. In many cases, the cache gets cleared with time elapsed or request frequency of key.
12 | There are two architectures for the pattern. 13 | 1. Cache input data. In this case, the service will request input data to DWH and cache parallelly, and proceed to prediction request if cache hits. If not hit, then you will add the data into the cache along with requesting the prediction. You may cache the data after preprocess, to decrease load for preprocessing.
14 | 2. Preprocess or cache before request. In this case, you will cache data prior to the prediction request, possibly along with the service's first data generation. Once you get a prediction request to the data, you will retrieve from cache to send to prediction. It is a good choice if you want to increase cache rate to improve latency. 15 | 16 | ## Diagram 17 | ### Input data cache 18 | ![diagram1](diagram1.png) 19 | 20 | ### Prepare data cache 21 | ![diagram2](diagram2.png) 22 | 23 | 24 | ## Pros 25 | - To offload request to prediction server and improve performance. 26 | - Able to respond quickly. 27 | 28 | ## Cons 29 | - Cache server cost. 30 | - Cache clear policy. 31 | 32 | ## Needs consideration 33 | - The input data should be able to get identified with key. 34 | - Tradeoff between speed, cost and volume. 35 | - Cache clear policy. 36 | - Data cache policy. 37 | 38 | 39 | ## Sample 40 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/data_cache_pattern 41 | -------------------------------------------------------------------------------- /Serving-patterns/Data-cache-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Data cache pattern 2 | 3 | ## Usecase 4 | - 同一データの推論リクエストが発生するワークフローの場合 5 | - 同じデータを繰り返し入力データとする場合 6 | - キャッシュのキーで検索可能な入力データの場合 7 | - データ処理を高速にしたい場合 8 | 9 | ## Architecture 10 | データ・キャッシュ・パターンは入力データをキャッシュするアーキテクチャです。入力データがデータベースやストレージにある場合、データをキャッシュしておくことでデータアクセスのオーバーヘッドを削減することが可能になります。
11 | キャッシュするデータ量はキャッシュのコストや容量とトレードオフになります。多くのキャッシュはストレージ等よりもコストが高く、容量が小さい傾向にあるので、コスト・オーバー、容量オーバーを避けるためにキャッシュクリアの方針が必要です。
12 | 使用するデータが時間経過で変化するシステムの場合、定期的にキャッシュクリアして古いキャッシュを削除する必要があります。高アクセスのシステムでキャッシュ容量が増大する場合、どのタイミングでどのキャッシュを削除するか、検討する必要があります。一般的にキャッシュクリアは時間経過やリクエスト頻度に応じて実行します。
 13 | このパターンは大きく2種類のアーキテクチャを考えることができます。
14 | 1つ目は入力データをキャッシュするパターンです。この場合、入力データの取得をDWHとキャッシュへ並列で実施し、キャッシュ・ヒットした場合はDWHへのアクセスを中止して後続の推論へ移行します。キャッシュ・ヒットしない場合は推論しつつ、取得したデータをキャッシュに保存します。同様の発想で入力データを前処理後にキャッシュするパターンも可能です。この場合、最初のデータは前処理してキャッシュに保存しますが、以降は同じ入力データであれば前処理せずにキャッシュから取得することが可能です。このパターンは前処理のオーバーヘッドを減らしたい場合に有効です。
15 | 2つ目のパターンはリクエストが来る前に前処理を済ませておくものです。データがDWHに投入された際にDWH等と連携して事前にデータ取得、前処理、キャッシュします。当該データを使うリクエストが入力された場合、キャッシュから前処理済みのデータを取得して推論に送ります。キャッシュ率を増強し、可能な限りキャッシュから推論することで速度を向上したい場合に有効なアーキテクチャになります。 16 | 17 | ## Diagram 18 | ### Input data cache 19 | ![diagram1](diagram1.png) 20 | 21 | ### Prepare data cache 22 | ![diagram2](diagram2.png) 23 | 24 | 25 | ## Pros 26 | - データ取得や前処理のオーバーヘッドを削減することができる。 27 | - 高速に推論を開始することが可能。 28 | 29 | ## Cons 30 | - キャッシュ・サーバのコストが発生。 31 | - キャッシュクリアの方針が必要。 32 | 33 | ## Needs consideration 34 | - メリットとキャッシュのコスト、容量とのトレードオフ。 35 | - キャッシュクリアのタイミング。 36 | - データをキャッシュするパターンの選定。 37 | 38 | 39 | ## Sample 40 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/data_cache_pattern 41 | -------------------------------------------------------------------------------- /Serving-patterns/Data-cache-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Data cache pattern 2 | 3 | ## Usecase 4 | - 동일하고 반복된 데이터에 대한 예측 요청이 있는 경우. 5 | - 캐시 키로 데이터를 식별할 수 있는 경우. 6 | - 데이터 검색 및 처리 속도를 높이고 싶은 경우. 7 | 8 | 9 | ## Architecture 10 | Data cache pattern은 입력 데이터를 캐시합니다. 입력 데이터가 데이터베이스, 저장소 또는 디스크에 저장되어 있으면 데이터 수집 오버헤드를 줄일 수 있습니다. 11 | 12 |
13 | 14 | 캐시할 데이터의 양은 비용과 사이즈의 균형에 따라 고려해야 할 수도 있습니다. 캐시 공간의 단가는 스토리지 또는 데이터베이스보다 크기가 작을수록 더 비싼 경향이 있으므로 캐시 삭제를 위한 정책을 계획하는 것을 추천합니다. 15 | 16 |
17 | 18 | 예측 결과가 시간에 따라 변경되면 오래된 예측으로 응답하지 않도록 이전 캐시를 지워야 합니다. 서비스 부하가 높아서 캐시 크기가 급격히 증가하는 경우 캐시 삭제 정책을 구체적으로 계획하는 것이 중요합니다. 대부분 캐시는 시간이 경과하거나 키 요청 빈도에 따라 지워집니다. 19 | 20 |
21 | 22 | 이 패턴에 대한 두 개의 아키텍처가 있습니다. 23 | 24 | 1. 입력 데이터를 캐시합니다. 이 경우 서비스는 데이터 웨어하우스에 입력 데이터를 요청하고 병렬로 캐시하며 캐시가 존재하면 예측 요청을 진행합니다. 캐시가 존재하지 않으면 데이터를 캐시에 추가하고 예측을 요청합니다. 전처리의 부하를 줄이기 위해 전처리 후 데이터를 캐시할 수 있습니다. 25 | 26 |
27 | 28 | 2. 요청하기 전에 전처리 또는 캐시합니다. 이런 경우 예측 요청 전에 서비스에서 첫 데이터 생성과 함께 데이터를 캐시합니다. 데이터에 대한 예측 요청을 받으면 캐시에서 예측을 검색합니다. 대기 시간을 개선하기 위해 캐시 속도를 높이려는 경우 이 방법이 선택하는 것이 좋습니다. 29 | 30 | 31 | ## Diagram 32 | ### Input data cache 33 | ![diagram1](diagram1.png) 34 | 35 | ### Prepare data cache 36 | ![diagram2](diagram2.png) 37 | 38 | 39 | ## Pros 40 | - 요청을 예측 서버로 오프로드하고 성능을 향상시킵니다. 41 | - 빠른 응답이 가능합니다. 42 | 43 | ## Cons 44 | - 캐시 서버 비용이 부과됩니다. 45 | - 캐시 삭제 정책이 필요합니다. 46 | 47 | ## Needs consideration 48 | - 입력 데이터는 키로 식별할 수 있어야 합니다. 49 | - 속도, 비용, 볼륨 간의 균형을 고려해야 합니다. 50 | - 캐시 삭제 정책이 필요합니다. 51 | - 데이터 캐시 정책이 필요합니다. 52 | 53 | ## Sample 54 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/data_cache_pattern 55 | -------------------------------------------------------------------------------- /Serving-patterns/Data-cache-pattern/diagram1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Data-cache-pattern/diagram1.png -------------------------------------------------------------------------------- /Serving-patterns/Data-cache-pattern/diagram2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Data-cache-pattern/diagram2.png -------------------------------------------------------------------------------- /Serving-patterns/Microservice-horizontal-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Microservice horizontal pattern 2 | 3 | ## Usecase 4 | - When the workflow can execute multiple predictions parallelly. 5 | - When you want to integrate prediction results at last. 6 | - Required to run several predictions to one request 7 | 8 | ## Architecture 9 | The microservice horizontal pattern enables you to run multiple independent models parallelly. You can send one request to the models at once to acquire multiple predictions, or an integrated prediciton. It is possible to respond with aggregated result, or just a specific prediction.
10 | You can decide to run on synchronous or asynchronous depending on your usecase. If you choose to do synchronously, it may be needed to respond the result after aggregated predictions from all the models. If asynchronous, then you can trigger the next action immediately once you get a specific prediction (`Asynchronized horizontal`).
11 | You may place a proxy in between client and prediction services. You may expect the proxy to control the data retrieval and prediction order away from the client. You may let the proxy or each predictors to do additional data retrieval (`Synchronized horizontal with data retrieval`). An advantage of proxy to get data is that it will decrease the number of requests to DWH or storage to reduce overhead, while the latter will let you control the data structure depending on each prediction model, that allows you to make complex workflow. 12 | 13 | ## Diagram 14 | ### Synchronized horizontal 15 | ![diagram1](diagram1.png) 16 | 17 | ### Synchronized horizontal with data retrieval 18 | ![diagram2](diagram2.png) 19 | 20 | ### Asynchronized horizontal 21 | ![diagram3](diagram3.png) 22 | 23 | ## Pros 24 | - You can tune resource usage independently and isolate failure. 25 | - You may develop model and system without having dependency on other models. 26 | 27 | ## Cons 28 | - The system may become complex. 29 | - For synchronous usecase, the slowest inference becomes bottleneck. 30 | - For asynchronous usecase, you have to let the postprocess to manage time lag between prediction latencies. 31 | 32 | ## Needs consideration 33 | - Synchronous or asynchronous. 34 | - How to manage slow model for synchronous: timeout or wait. 35 | - How to manage time lag for asynchronous. 36 | 37 | ## Sample 38 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/horizontal_microservice_pattern 39 | -------------------------------------------------------------------------------- /Serving-patterns/Microservice-horizontal-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Microservice horizontal pattern 2 | 3 | ## Usecase 4 | - 依存関係のない複数の推論を平行して実行するとき 5 | - 複数の推論結果を最後に集計するワークフローのとき 6 | - 1データに対して複数の推論結果が必要なとき 7 | 8 | ## Architecture 9 | 依存関係のない複数の推論モデルを平行して実行するのが並列マイクロサービス・パターンです。並列マイクロサービス・パターンでは各推論サーバに平行して推論リクエストを送信することで、複数の推論結果を得ることができます。要件に応じて、複数の推論結果を集計することや、特定の推論結果のみをレスポンスすることも可能です。
10 | 推論は用途によって同期的・非同期的に実行する方針を決める必要があります。同期的に実行するユースケースとしては、全推論を得てから結果を集計する場合が考えられます。非同期的に実行する場合は、推論を得たら即時にアクションを取るユースケースが考えられます(`Asynchronized horizontal`)。
11 | クライアントと推論サーバの間には推論を仲介するプロキシを置くことが可能です。プロキシを配置することでデータ取得や推論結果の集約等のタスクをクライアントから隔離することが期待できます。推論のための入力データはプロキシで一括して収集することも、各推論サーバで取得することも可能です(`Synchronized horizontal with data retrieval`)。前者のメリットはDWHやストレージへのアクセス回数を減らし、オーバーヘッドを削減できることです。後者のメリットは各モデルが必要なデータを取得することで、複雑なフローを実現することができます。 12 | 13 | ## Diagram 14 | ### Synchronized horizontal 15 | ![diagram1](diagram1.png) 16 | 17 | ### Synchronized horizontal with data retrieval 18 | ![diagram2](diagram2.png) 19 | 20 | ### Asynchronized horizontal 21 | ![diagram3](diagram3.png) 22 | 23 | ## Pros 24 | - 推論サーバを分割することでリソース調整や障害分離が可能。 25 | - 推論のワークフロー間で依存関係を持たせず、柔軟にシステムを構築することができる。 26 | 27 | ## Cons 28 | - 複数の推論を稼働させるため、システムが複雑になることがある。 29 | - 同期的に実行する場合、所要時間が最遅の推論に依存する。 30 | - 非同期に実行する場合、推論器どうしの所要時間の差を後段のワークフローで吸収する必要がある。 31 | 32 | ## Needs consideration 33 | - 推論を同期的に実行するか、非同期的に実行するか。 34 | - 同期的に実行する場合、遅い推論をタイムアウトするか等の検討が必要。 35 | - 非同期的に実行する場合、推論の所要時間差の検討が必要。 36 | 37 | ## Sample 38 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/horizontal_microservice_pattern 39 | -------------------------------------------------------------------------------- /Serving-patterns/Microservice-horizontal-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Microservice horizontal pattern 2 | 3 | ## Usecase 4 | - 워크플로우가 여러 예측을 병렬로 실행할 수 있는 경우. 5 | - 마지막에 예측 결과를 통합하고 싶은 경우. 6 | - 하나의 요청에 여러 예측을 하고 싶은 경우. 7 | 8 | 9 | ## Architecture 10 | Microservice horizontal pattern은 여러 독립적인 모델을 병렬로 실행할 수 있습니다. 한번에 여러 모델에 예측을 요청해 여러 예측 결과나 통합된 예측 결과를 얻을 수 있습니다.
11 | 활용 사례에 따라 동기 또는 비동기 방식 중 어떤 것을 사용할지 결정할 수 있습니다. 만약 동기 방식을 사용하면, 모든 모델의 예측 결과를 집계해 반환해야 합니다. 만약 비동기 방식을 사용하면, 특정 예측(`Asynchronized horizontal`)이 나오면 바로 다음 작업을 실행할 수 있습니다.
12 | 클라이언트와 예측 서비스 사이에 프록시를 배치할 수도 있습니다. 프록시가 클라이언트에서 요청하는 데이터 검색 및 예측 순서를 제어하기를 기대할 수 있습니다. 프록시 또는 예측 서비스가 추가 데이터 검색을 수행하도록 할 수 있습니다(`Synchronized horizontal with data retrieval`). 데이터를 가져오는 프록시의 장점은 데이터웨어하우스 또는 스토리지에 대한 요청 수를 줄여 오버헤드를 줄이는 반면, 후자는 각 예측 모델에 따라 데이터 구조를 제어해 복잡한 워크플로우를 만들 수 있습니다. 13 | 14 | ## Diagram 15 | ### Synchronized horizontal 16 | ![diagram1](diagram1.png) 17 | 18 | ### Synchronized horizontal with data retrieval 19 | ![diagram2](diagram2.png) 20 | 21 | ### Asynchronized horizontal 22 | ![diagram3](diagram3.png) 23 | 24 | ## Pros 25 | - 리소스 사용량을 독립적으로 조정하고 장애를 격리할 수 있습니다. 26 | - 다른 모델에 의존성 없이 모델과 시스템을 개발할 수 있습니다. 27 | 28 | ## Cons 29 | - 시스템이 복잡해질 수 있습니다. 30 | - 동기 방식은 가장 느린 예측이 병목이 됩니다. 31 | - 비동기 방식은 예측 지연 시간을 관리하도록 사후 처리를 해야 합니다. 32 | 33 | ## Needs consideration 34 | - 동기식 또는 비동기식. 35 | - 동기식에서 느린 모델을 관리하는 방법 : 타임아웃 또는 대기. 36 | - 비동기식에서 시간 지연을 관리하는 방법. 37 | 38 | ## Sample 39 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/horizontal_microservice_pattern 40 | -------------------------------------------------------------------------------- /Serving-patterns/Microservice-horizontal-pattern/diagram1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Microservice-horizontal-pattern/diagram1.png -------------------------------------------------------------------------------- /Serving-patterns/Microservice-horizontal-pattern/diagram2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Microservice-horizontal-pattern/diagram2.png -------------------------------------------------------------------------------- /Serving-patterns/Microservice-horizontal-pattern/diagram3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Microservice-horizontal-pattern/diagram3.png -------------------------------------------------------------------------------- /Serving-patterns/Microservice-vertical-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Microservice vertical pattern 2 | 3 | ## Usecase 4 | - When you need to run several inferences in order 5 | - When you have several inferences, and they have dependencies 6 | 7 | ## Architecture 8 | The microservice vertical pattern allows you to run multiple model in order. The pattern deploys prediction models in separate servers or containers as service. You execute prediction request from top to bottom synchronously, and gather the results to respond to the client. If there is dependencies of order for one another, the microservice vertical pattern is a good choice. It also allows you to separate maintenance lifecycle as well as fault isolation for deploying the servers independently.
9 | You may place a proxy in between client and prediction services. You may expect the proxy to control the data retrieval and prediction order away from the client. You may let the proxy or each predictors to do additional data retrieval (`Diagram2`). An advantage of proxy to get data is that it will decrease the number of requests to DWH or storage to reduce overhead, while the latter will let you control the data structure depending on each prediction model, that allows you to make complex workflow. 10 | 11 | 12 | ## Diagram 13 | ### Diagram1 14 | ![diagram1](diagram1.png) 15 | 16 | ### Diagram2 17 | ![diagram2](diagram2.png) 18 | 19 | ## Pros 20 | - You may run multiple predictions in order. 21 | - It is possible to select next prediction service depending on the former prediction. 22 | - You may make the resource usage efficient, independent in server and code, and isolate failure. 23 | 24 | ## Cons 25 | - Since the predictions run synchronous order, it will require higher latency. 26 | - A former prediction latency may be bottleneck. 27 | - Complex system structure and workflow. 28 | 29 | ## Needs consideration 30 | - You may need to consider concrete performance tuning to meet required service level. 31 | - The system structure will become complex. It is better to try to make the interfaces and servers common. -------------------------------------------------------------------------------- /Serving-patterns/Microservice-vertical-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Microservice vertical pattern 2 | 3 | ## Usecase 4 | - 1操作に対して複数の推論を実行するとき 5 | - 複数の推論間で実行順や依存関係があるとき 6 | 7 | ## Architecture 8 | 複数の推論モデルを順列に実行するときのアーキテクチャとして直列マイクロサービス・パターンがあります。直列マイクロサービス・パターンでは、複数の機械学習モデルを別サーバで並列して配置します。それぞれに順番に(同期的に)推論リクエストを送信し、最後の推論を集計した後に推論結果を得ます。各機械学習モデル間で実行順の依存関係がある場合、直列マイクロサービス・パターンが有効です。推論モデルを個別のサーバに配置するため、各モデルの更新やサーバ障害を他のモデルやサーバから分離することが可能です。
9 | クライアントと推論サーバの間には推論を仲介するプロキシを置くことが可能です。プロキシを配置することでデータ取得や推論順の制御をクライアントから隔離することが期待できます。推論のための入力データはプロキシで一括して収集することも、各推論サーバで取得することも可能です(`Diagram2`)。前者のメリットはDWHやストレージへのアクセス回数を減らし、オーバーヘッドを削減できることです。後者のメリットは各モデルや前の推論次第で取得するデータを制御できることで、複雑なフローを実現することができます。 10 | 11 | 12 | ## Diagram 13 | ### Diagram1 14 | ![diagram1](diagram1.png) 15 | 16 | ### Diagram2 17 | ![diagram2](diagram2.png) 18 | 19 | ## Pros 20 | - 各推論モデルを順番に実行することが可能。 21 | - 前の推論モデルの結果次第で次モデルの推論リクエスト先を選択する構成も可能。 22 | - 各推論でサーバやコードベースを分割することで、リソースの効率化や障害分離が可能。 23 | 24 | ## Cons 25 | - 複数の推論を順番に実行するため、所要時間が長くなることがある。 26 | - 前の推論結果を得られないと次の推論を実行することができず、ボトルネックになる。 27 | - システム構成が複雑になる可能性がある。 28 | 29 | ## Needs consideration 30 | - 各推論モデルの所要時間の和が結果を得るまでの所要時間になるため、パフォーマンス・チューニングが必要。 31 | - システム構成が複雑になるため、インターフェイスやサーバ等を共通化しシンプルに構成することが望ましい。 -------------------------------------------------------------------------------- /Serving-patterns/Microservice-vertical-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Microservice vertical pattern 2 | 3 | ## Usecase 4 | - 순서대로 여러 예측을 해야하는 경우 5 | - 여러 예측이 있고, 예측끼리 의존 관계가 있는 경우 6 | 7 | ## Architecture 8 | Microservice vertical pattern을 사용하면 여러 모델을 순서대로 실행할 수 있습니다. 이 패턴은 별도의 서버 또는 컨테이너에 예측 모델을 배포합니다. 예측 요청을 위에서 아래로 동기적으로 실행하고, 결과를 수집해 클라이언트에 응답합니다. 서로에 대한 순서 종속성이 있는 경우 마이크로서비스 수직 패턴을 선택하는 것이 좋습니다. 서버를 독립적으로 배포하기 위해 유지관리 라이프사이클과 장애 격리를 분리할 수 있습니다.
9 | 클라이언트와 예측 서버 사이에 프록시를 둘 수 있습니다. 이 프록시 배치를 통해 클라이언트로부터 데이터 검색 및 예측 순서 제어 분리를 기대할 수 있습니다. 프록시나 각 예측 서버에 추가 데이터 검색을 할 수 있습니다(`Diagram2`). 데이터를 얻는 프록시의 장점은 오버헤드를 줄이기 이해 데이터 웨어하우스 또는 스토리지의 요청 수를 줄이는 반면, 후자는 복잡한 워크플로우를 만들 수 있는 각 예측 모델에 따라 데이터 구조를 제어할 수 있습니다. 10 | 11 | 12 | ## Diagram 13 | ### Diagram1 14 | ![diagram1](diagram1.png) 15 | 16 | ### Diagram2 17 | ![diagram2](diagram2.png) 18 | 19 | ## Pros 20 | - 여러 예측을 순서대로 실행할 수 있습니다. 21 | - 이전 예측 결과에 따라 다음 예측 서비스를 선택할 수 있습니다. 22 | - 리소스를 효율적으로 사용하고, 서버와 코드를 독립하고, 장애를 격리할 수 있습니다. 23 | 24 | ## Cons 25 | - 예측이 동기식으로 실행되므로 대기 시간이 더 필요할 것입니다. 26 | - 이전 예측 지연으로 병목이 될 수 있습니다. 27 | - 복잡한 시스템 구조와 워크플로우 28 | 29 | ## Needs consideration 30 | - 필요한 서비스 수준을 만족하기 위해, 구체적인 성능 튜닝을 고려할 필요가 있습니다. 31 | - 시스템 구조가 복잡해질 수 있기 때문에 인터페이스와 서버들을 공통화하는 것이 좋습니다. 32 | -------------------------------------------------------------------------------- /Serving-patterns/Microservice-vertical-pattern/diagram1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Microservice-vertical-pattern/diagram1.png -------------------------------------------------------------------------------- /Serving-patterns/Microservice-vertical-pattern/diagram2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Microservice-vertical-pattern/diagram2.png -------------------------------------------------------------------------------- /Serving-patterns/Multiple-stage-prediction-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Multiple stage prediction pattern 2 | 3 | ## Usecase 4 | - To use ML prediction for interactive application. 5 | - When you have lightweight prediction and heavy prediction for one purpose. 6 | 7 | ## Architecture 8 | The multiple stage prediction pattern is available when its workflow is to respond to its client in multiple stages. ML model in general tends to be lightweight for table and numerical data, while heavy for unstructured data, such as image and text. Some services require to have a quick response, with adding better prediction later to improve user experience. For web applications, it is important to take a balance of speed and accuracy, and especially for interactive applications, it is possible to consider a usecase where you first return a quick prediction, and then add the better ones in the next screen or downward. The pattern is effective to these interactive applications.
9 | The pattern contains two prediction servers. One is to respond quick synchronously, and another one to predict later asynchronously. The first one is used to respond quickly with a fare accuracy using REST or GRPC interface. The latter will be slower, so asynchronous queue or messaging service is useful. The models to be in production depends on the requirement for the quality of prediction and speed to respond, though it might be separated with the data to be used, for instance numerical and categorical data for the synchronous prediction, and the image and text for the asynchronous, if the system uses multiple modality. 10 | 11 | ## Diagram 12 | ![diagram](diagram.png) 13 | 14 | 15 | ## Pros 16 | - Respond quickly and then predict better. 17 | 18 | ## Cons 19 | - You need multiple services and interfaces. 20 | 21 | ## Needs consideration 22 | - Balance of speed, accuracy and user experience. 23 | - How to provide the heavy predictions. -------------------------------------------------------------------------------- /Serving-patterns/Multiple-stage-prediction-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Multiple stage prediction pattern 2 | 3 | ## Usecase 4 | - インタラクティブなアプリケーションに推論を組み込むとき 5 | - 速い推論器と遅い推論器を組み合わせるとき 6 | 7 | ## Architecture 8 | マルチ・ステージ推論パターンは推論結果を複数段階に分けてクライアントにレスポンスする場合に有効な構成です。機械学習では一般的に、構造化データを扱うモデルは推論が高速で、画像やテキスト等の非構造化データを扱う場合は遅くなる傾向にあります。サービスの使われ方として、リクエストに対して素早くレスポンスを返す必要がある一方で、多少遅れてでもより良い結果を返すことでユーザ体験を改善できることもあります。WebアプリケーションでMLを扱う場合、スピードと精度のバランスが重要になりますが、インタラクティブな使われ方がされるのであれば、すぐに簡単な推論結果を返して表示した後に、ユーザの使用中により良い推論結果を次の画面(またはスクロールした画面等々)に用意しておく、というライフサイクルが考えられます。本パターンはそうしたインタラクティブなアプリケーションで効果を発揮するものです。
9 | 本パターンは2種類の推論器を配置します。素早く同期的に推論結果をレスポンスする推論器と、非同期で処理の重い推論器です。前者はリクエストに対して素早くレスポンスを返すため、REST APIやGRPC等をインターフェイスとすると良いでしょう。後者は処理時間が発生するため、非同期なキューやメッセージングが有効です。前者と後者で搭載するモデルの種類はクライアントにレスポンスするスピードおよび推論の精度次第ですが、例えば入力データが数字、カテゴリ、画像、自然言語等の組み合わせになる場合、前者には計算量が少なくて済む数字とカテゴリ、後者で画像と自然言語を扱う、という分担が考えられます。 10 | 11 | ## Diagram 12 | ![diagram](diagram.png) 13 | 14 | 15 | ## Pros 16 | - 素早くレスポンスしつつ、より良い推論結果も提供することが可能 17 | 18 | ## Cons 19 | - 複数のインターフェイスと推論器を用意するため、運用負荷が増える 20 | 21 | ## Needs consideration 22 | - 推論器のスピードと精度 23 | - 遅い推論器の結果の出し方 -------------------------------------------------------------------------------- /Serving-patterns/Multiple-stage-prediction-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Multiple stage prediction pattern 2 | 3 | ## Usecase 4 | - 대화식 애플리케이션에서 머신러닝 예측을 사용할 경우. 5 | - 하나의 목적에 가벼운 모델과 무거운 모델이 있는 경우. 6 | 7 | ## Architecture 8 | Multiple stage prediction pattern은 워크플로우가 여러 단계로 클라이언트에 응답하는 경우 사용할 수 있습니다. 일반적으로 머신러닝 모델은 테이블 및 숫자 데이터를 사용할 경우 가벼운 경향이 있는 반면, 이미지나 텍스트 같은 비정형 데이터는 무거운 경향이 있습니다. 일부 서비스는 사용자 경험을 개선하기 위해 더 나은 예측을 추가해 빠른 응답을 요구합니다. 웹 애플리케이션은 속도와 정확도의 균형을 유지하는 것이 중요하며, 대화형 애플리케이션은 먼저 빠른 예측을 반환한 후 다음 화면 또는 아래쪽에 더 좋은 예측을 추가하는 방법을 고려할 수 있습니다. 이 패턴은 대화형 애플리케이션에 효과적입니다. 9 | 10 |
11 | 12 | 이 패턴은 두 개의 예측 서버가 존재합니다. 하나는 빠른 동기식으로 응답하고 다른 하나는 나중에 비동기식으로 예측하는 서버입니다. 첫 서버는 REST 또는 GRPC 인터페이스를 사용해 무난한 정확도를 가진 예측을 빠르게 응답하는데 사용됩니다. 후자는 느리므로 비동기 대기열 또는 메세지 서비스가 유용합니다. 프러덕션 모델은 여러 형태를 사용할 경우 예를 들어 동기식 예측을 위한 수치 및 범주형 데이터, 비동기식 예측을 위한 영상과 텍스트 같이 사용될 데이터로 분리될 수 있지만, 예측 품질과 응답 속도의 요구 사항에 따라 달라집니다. 13 | 14 | 15 | ## Diagram 16 | ![diagram](diagram.png) 17 | 18 | 19 | ## Pros 20 | - 빠르게 대응하고 그 후 더 잘 예측합니다. 21 | 22 | ## Cons 23 | - 여러 서비스와 인터페이스가 필요합니다. 24 | 25 | ## Needs consideration 26 | - 속도, 정확도, 유저 경험의 균형을 맞춰야 합니다. 27 | - 무거운 예측을 제공하는 방법에 대해 고민해야 합니다. 28 | -------------------------------------------------------------------------------- /Serving-patterns/Multiple-stage-prediction-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Multiple-stage-prediction-pattern/diagram.png -------------------------------------------------------------------------------- /Serving-patterns/Prediction-cache-pattern/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Please read the CLA carefully before submitting your contribution to Mercari. 4 | Under any circumstances, by submitting your contribution, you are deemed to accept and agree to be bound by the terms and conditions of the CLA. 5 | 6 | https://www.mercari.com/cla/ -------------------------------------------------------------------------------- /Serving-patterns/Prediction-cache-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Prediction cache pattern 2 | 3 | ## Usecase 4 | - When your service may get prediction request on same data, and can identify it. 5 | - The prediction result may not change so frequently. 6 | - The input data can be searched with cache. 7 | - To accelerate prediction and offload. 8 | 9 | ## Architecture 10 | In the prediction cache pattern, you will store predicted result into a cache to make it possible to search for the later request for the repeated data. If your service gets requests for same data, and if it is possible to identify it is the same, you can get advantage of the pattern.
11 | The prediction server or proxy will store input data as cache key with prediction as value, if the key does not exist. After the cache, the cache search and prediction will be executed parallelly and returns the value if the cache hits without waiting for the prediction completes. It will shorten the amount of time taken to predict with less load to the prediction server.
12 | The amount of data to cache may need to be considered with balance of cost and volume. The unit price for cache space tends to be higher with less size than storage or database, hence it is recommended to plan a policy to clear cache.
13 | If the prediction result changes with time, it requires to clear old cache to prevent responding with outdated prediction. If the service gets high load that the cache size increases rapidly, it is important to plan cache clear policy concretely. In many cases, the cache gets cleared with time elapsed or request frequency of key. 14 | 15 | ## Diagram 16 | ### Prediction cache 17 | ![diagram](diagram.png) 18 | 19 | 20 | ## Pros 21 | - To offload request to prediction server and improve performance. 22 | - Able to respond quickly. 23 | 24 | ## Cons 25 | - Cache server cost. 26 | - Cache clear policy. 27 | 28 | ## Needs consideration 29 | - The input data should be able to get identified with key. 30 | - Tradeoff between speed, cost and volume. 31 | - Cache clear policy. 32 | 33 | ## Sample 34 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/prediction_cache_pattern 35 | -------------------------------------------------------------------------------- /Serving-patterns/Prediction-cache-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Prediction cache pattern 2 | 3 | ## Usecase 4 | - 同一データの推論リクエストが発生し、かつ同一データを同定できるワークフローの場合 5 | - 推論結果が時間経過で変わる可能性が低いとき 6 | - キャッシュのキーで検索可能な入力データの場合 7 | - 推論を高速に処理したい場合 8 | 9 | ## Architecture 10 | 推論キャッシュ・パターンは推論結果をキャッシュに格納することで、同一データの推論をキャッシュ検索することができるようになります。同一データに対する推論が多く、入力データの同定をキャッシュキーで検索できる場合、推論キャッシュ・パターンは有効です。
11 | 本パターンでは入力データがキャッシュに存在しない場合、推論後に入力データをキー、推論結果を値としてキャッシュに格納します。以降の推論では、キャッシュを検索と推論を同時に実行し、キャッシュにヒットした場合は推論のレスポンスを待たずに値をクライアントに返却します。機械学習の推論にかかる時間を短縮し、推論サーバへの負荷を削減することが期待できます。
12 | キャッシュするデータ量はキャッシュのコストや容量とトレードオフになります。多くのキャッシュはストレージ等よりもコストが高く、容量が小さい傾向にあるため、コスト・オーバー、容量オーバーを避けるためにキャッシュクリアの方針が必要です。
13 | 推論結果が時間経過で変化するシステムの場合、定期的にキャッシュクリアして古いキャッシュを削除する必要があります。高アクセスのシステムでキャッシュ容量が増大する場合、どのタイミングでどのキャッシュを削除するか、検討する必要があります。キャッシュクリアは時間経過やリクエスト頻度に応じて実行することが多いです。 14 | 15 | ## Diagram 16 | ### Prediction cache 17 | ![diagram](diagram.png) 18 | 19 | 20 | ## Pros 21 | - 推論速度を改善し、推論サーバへの負荷をオフロードすることが可能。 22 | - 高速に推論結果をレスポンス可能。 23 | 24 | ## Cons 25 | - キャッシュ・サーバのコストが発生。 26 | - キャッシュクリアの方針が必要。 27 | 28 | ## Needs consideration 29 | - 入力データを同定できるか検討する必要がある。 30 | - メリットとキャッシュのコスト、容量とのトレードオフ。 31 | - キャッシュクリアのタイミング。 32 | 33 | ## Sample 34 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/prediction_cache_pattern 35 | -------------------------------------------------------------------------------- /Serving-patterns/Prediction-cache-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Prediction cache pattern 2 | 3 | ## Usecase 4 | - 동일한 데이터에 대한 예측 요청을 받고, 동일한 데이터를 식별할 수 있는 경우. 5 | - 예측 결과가 자주 변경되지 않는 경우. 6 | - 입력 데이터는 캐시로 검색할 수 있습니다. 7 | - 예측과 오프로드를 가속화합니다. 8 | 9 | ## Architecture 10 | Prediction cache pattern은 예측 결과를 캐시에 저장해 나중에 반복되는 동일한 데이터에 대한 요청을 검색할 수 있습니다. 서비스가 동일한 데이터에 대해 요청을 받고, 동일 데이터를 식별할 수 있는 경우에 이 패턴이 이점을 가집니다.
11 | 예측 서버 또는 프록시는 입력 데이터를 캐시 key로 저정하고 키가 없는 경우 예측 결과를 value로 저장합니다. 캐시가 끝나면 캐시 검색과 예측이 병렬로 실행되며 예측이 완료되기를 기다리지 않고 캐시가 히트하면 값을 반환합니다. 예측 서버에 대한 부하를 줄여 예측에 걸리는 시간을 단축됩니다.
12 | 캐시할 데이터 양은 비용과 볼륨의 균형을 고려해야할 수 있습니다. 캐시 공간의 단가는 더 작은 스토리지나 데이터베이스보다 비싼 경향이 있으므로 캐시 삭제 정책을 만드는 것을 추천합니다.
13 | 예측 결과가 시간이 지나며 변하는 경우, 오래된 예측으로 응답하지 않도록 오래된 캐시를 지워야 합니다. 캐시 크기가 빠르게 증가할 정도로 서비스 로드가 높아지면, 캐시 삭제 정책을 구체적으로 설정하는 것이 중요합니다. 대부분 시간이 경과하거나 키의 요청 빈도에 따라 캐시가 지워집니다. 14 | 15 | ## Diagram 16 | ### Prediction cache 17 | ![diagram](diagram.png) 18 | 19 | 20 | ## Pros 21 | - 요청을 예측 서버로 오프로드 가능하고, 성능을 개선할 수 있습니다. 22 | - 응답이 빠를 수 있습니다. 23 | 24 | ## Cons 25 | - 캐시 서버 비용. 26 | - 캐시 정리 정책. 27 | 28 | ## Needs consideration 29 | - 입력 데이터로 고유하게 식별이 가능해야 합니다. 30 | - 속도, 비용, 볼륨의 트레이드오프를 고려해야 합니다. 31 | - 캐시 정리 정책이 필요합니다. 32 | 33 | ## Sample 34 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/prediction_cache_pattern 35 | -------------------------------------------------------------------------------- /Serving-patterns/Prediction-cache-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Prediction-cache-pattern/diagram.png -------------------------------------------------------------------------------- /Serving-patterns/Prediction-circuit-break-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Prediction circuit break pattern 2 | 3 | ## Usecase 4 | - When there is a possibility that amount or frequency of request to prediction suddenly increases. 5 | - If it is not applicable to scale out so quick to respond the sudden request. 6 | - If it is not needed to respond 100%. 7 | 8 | ## Architecture 9 | There are occasions when the number of access to the web service, or related service, suddenly increases due to a campaign or external event. If you are using cloud service or Kubernetes, you can scale out your service to respond the requests, though there are many cases that the increase in amount of request is way beyond the speed of scale out. Especially when the server or container image contains model file, launching or downloading it may take a file.
10 | The prediction circuit breaker pattern is an architecture to avoid `complete outage` until the scale out succeeds. It allows to predict as much as predictable, with cancelling requests more than a certain limit before reaching the prediction server. Thinking that the complete outage is the worst case, you may take into account that a partial outage is rather reasonable. It often happens that with high tide of request that the prediction server restarts which lessens prediction resource. It is reasonable to choose to cancel a certain number of request to stabilize the current prediction service, until the scale out completes to respond all the predictions.
11 | The important point of the pattern is to have a fallback plan for cancelled requests. You have to minimize lowering user experience, and avoid stopping client activity. It is recommended to consider a workflow for cancellation. 12 | 13 | ## Diagram 14 | ![diagram](diagram.png) 15 | 16 | ## Pros 17 | - Avoid complete outage of the service. 18 | - It allows to scale out prediction servers without lowering the current resource availability. 19 | 20 | ## Cons 21 | - Require fallback plan for cancelled request. 22 | 23 | ## Needs consideration 24 | - Fallback plan and workflow for cancellation. 25 | - The circuit breaking limit should be high enough to respond on usual increase in service request. -------------------------------------------------------------------------------- /Serving-patterns/Prediction-circuit-break-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Prediction circuit break pattern 2 | 3 | ## Usecase 4 | - 推論へのアクセスが急激に増減する場合 5 | - 急激なアクセス増減に推論サーバやインフラが対応できない場合 6 | - 全リクエストへレスポンスを返す必要がない場合 7 | 8 | ## Architecture 9 | Webサービスではキャンペーンや不慮の事件等によってアクセスが急激に増加することがあります。そうした場合、クラウドやKubernetesではスケールアウトすることによって増加したアクセスに対応することが可能ですが、リソースのスケールアウトよりもアクセス増のほうが急速に発生することが一般的です。特にモデルファイル等を含み、サーバやコンテナのイメージの容量が大きい傾向にある推論サーバでは、リソースの起動は時間を要する傾向にあります。
10 | 推論サーキットブレーカー・パターンはリソース増加が完了するまでの時間、推論サーバを「全断」させないためのアーキテクチャーです。本パターンでは一定以上の頻度で発生するリクエストをプロキシで遮断することによって、推論サーバに送信されるリクエスト数を処理可能な量に制限します。サービスが全断する事態を最悪とすれば、一部のリクエストのみを遮断することでサービスを継続する、という発想です。高負荷によって推論サーバが停止、再起動する可能性を鑑みれば、既存の推論サーバは正常な状態を維持し、スケールアウトによって高負荷に耐える推論サーバ数になるまで一部のリクエストを遮断するのは、理にかなったアーキテクチャーになります。
11 | 推論サーキットブレーカー・パターンを構成する際に重要なのは、遮断されたリクエストへのフォールバック・プランです。遮断されたことによってクライアントが停止し、後続のワークフローが破綻することは避けるべきです。遮断した場合のワークフローや注意書き等、アプリケーションを停止しない方法を用意することが重要です。 12 | 13 | ## Diagram 14 | ![diagram](diagram.png) 15 | 16 | ## Pros 17 | - 負荷が急激に増加してもサービス全体を停止しない。 18 | - 推論サーバを停止せず、安全にスケールアウトすることが可能。 19 | 20 | ## Cons 21 | - 遮断された一部のリクエストに対するフォールバック・プランが必要。 22 | 23 | ## Needs consideration 24 | - 遮断されたリクエストへのフォールバック・プラン。 25 | - サーキットブレーカーの値が低すぎてほとんどのリクエストを処理できない場合は、そもそものアーキテクチャーやリソースを再検討する必要あり。 26 | -------------------------------------------------------------------------------- /Serving-patterns/Prediction-circuit-break-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Prediction circuit break pattern 2 | 3 | ## Usecase 4 | - 예측 요청량 또는 빈도가 갑자기 증가할 가능성이 있는 경우. 5 | - 갑작스러운 요청에 빠르게 응답할만큼 빠르게 스케일 아웃할 수 없는 경우. 6 | - 100% 응답할 필요가 없는 경우. 7 | 8 | ## Architecture 9 | 캠페인이나 외부 이벤트 때문에 웹 서비스나 관련 서비스에 접속이 증가하는 경우가 있습니다. 만약 클라우드 서비스 또는 쿠버네티스를 사용한다면 요청량만큼 스케일 아웃을 할 수 있지만, 스케일 아웃 속도보다 요청량이 증가하는 속도가 더 빠른 경우가 많습니다. 특히 서버 또는 컨테이너 이미지에 모델 파일이 포함된 경우, 모델을 실행하거나 다운로드 받는데 시간이 오래 걸릴 수 있습니다. 10 | 11 |
12 | Prediction circuit breaker pattern은 스케일 아웃이 성공할 때까지 `complete outage`를 방지하는 아키텍처입니다. 예측 서버가 예측할 수 있을 만큼 예측하고, 특정 한계 이상으로 요청이 오면 예측을 취소합니다. 전체 중단이 최악의 경우라 생각하면 부분 중단이 합리적이라고 생각할 수 있습니다. 요청이 많으면 예측 서버가 다시 시작되어 예측 리소스가 줄어드는 경우가 자주 발생합니다. 모든 예측에 응답하기 위해 스케일 아웃이 완료될 때까지 현재 예측 서비스를 안정화해야 하고, 안정화를 위해 특정 수의 요청을 취소하는 것이 합리적입니다. 13 | 14 |
15 | 16 | 이 패턴의 중요한 점은 취소된 요청에 대한 대안을 세우는 것입니다. 사용자 경험 저하를 최소화하고 클라이언트 활동을 중단하지 않아야 합니다. 취소를 위한 워크플로우를 고려하는 것이 좋습니다. 17 | 18 | 19 | ## Diagram 20 | ![diagram](diagram.png) 21 | 22 | ## Pros 23 | - 서비스의 완전한 중단을 피합니다. 24 | - 현재 리소스 가용성을 낮추지 않고 예측 서버를 확장할 수 있습니다. 25 | 26 | ## Cons 27 | - 취소된 요청에 대한 대안이 필요합니다. 28 | 29 | ## Needs consideration 30 | - 취소된 요청에 대한 대안 및 워크플로우. 31 | - circuit breaking limit은 일반적 서비스 요청 증가에 대응할 수 있을만큼 높아야 합니다. 32 | -------------------------------------------------------------------------------- /Serving-patterns/Prediction-circuit-break-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Prediction-circuit-break-pattern/diagram.png -------------------------------------------------------------------------------- /Serving-patterns/Prep-pred-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Preprocess-prediction pattern 2 | 3 | ## Usecase 4 | - When you have different code-base, library or resource load requirements for preprocess and prediction. 5 | - When you want to separate preprocess with prediction to divide issue in each resource to improve availability. 6 | 7 | ## Architecture 8 | There are cases when the requirements for preprocess and the one for prediction are different. Usually the preprocess runs normalization or standardization for numericals, one-hot encoding for categories, vocab filtering for NLP, resizing for image, and so forth, and they can be pretrained or can be rule-based. On the other hand, the prediction implies pretrained and built, or binalized, model file that can take input to return inference. The preprocess maybe just defined in Python, and the prediction model may be built with Tensorflow or ONNX in binary. These differences enables to build separate servers or containers to optimize development and operation of each resource.
9 | Since you divide preprocess and prediction model into separate resources, you need to consider tuning, network connection, versioning for each of them. It makes the system complex than the [web single pattern](../Web-single-pattern/design_en.md), while the preprocess-prediction pattern enables you to use the serving resource efficient, as well as independent development and fault isolation. There are many cases to apply the pattern in case of using deep learning for inference.
10 | The `diagram2` shows deploying a proxy in front of the preprocess and prediction, to make them as microservices. In this case, the proxy will mediate data retrieval, preprocess and prediction services. It will allow you to develop those resources separately with independent library, language and infrastructure. However, it will add components to manage that requires you to understand all the components to troubleshoot in case of incident. 11 | 12 | ## Diagram 13 | ### Simple prep-pred pattern 14 | ![diagram1](diagram1.png) 15 | 16 | ### Microservice prep-pred pattern 17 | ![diagram2](diagram2.png) 18 | 19 | ## Pros 20 | - Able to use resource efficiently with fault isolation. 21 | - Flexibility in resource usage and scalability. 22 | - Able to select library and language versions for each component. 23 | 24 | ## Cons 25 | - Increases operation cost with complexity in resources. 26 | - Network connection in between preprocess and prediction may become bottleneck. 27 | 28 | ## Needs consideration 29 | - Since it is impossible to train a whole model, including preprocess and prediction, independently, you still have to tune parameters in one training. 30 | - If you happen to develop preprocess and prediction separately, there may not cause trouble as system, though may cause incorrectness in prediction. 31 | - You have to tune resources separately. 32 | 33 | ## Sample 34 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/prep_pred_pattern 35 | -------------------------------------------------------------------------------- /Serving-patterns/Prep-pred-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Preprocess-prediction pattern 2 | 3 | ## Usecase 4 | - 前処理と推論でライブラリやコードベース、リソース負荷が違うとき 5 | - 前処理と推論を分割することで障害分離し、可用性を向上させたいとき 6 | 7 | ## Architecture 8 | 推論器の前処理と推論で必要なリソースが違うことがあります。前処理では数値の標準化や正規化、カテゴリのone-hot encoding、自然言語の形態素解析、画像のリサイズ、補完データの取得等が実行されます。推論では各機械学習ライブラリでモデルがビルド(バイナリ化)されており、データを入力すれば推論が得られる構成になっていることが多いです。前処理がPythonでスクリプトとして書かれている一方、ビルドされた機械学習モデルはバイナリ化されていることもあります(例:Tensorflow servingやONNX)。そのため、前処理と推論でサーバやコンテナを分割し、開発と運用を効率化することができます。
9 | 前処理器と推論器を分割するため、それぞれのリソース・チューニングや相互のネットワーク設計、バージョニングが必要になります。[Webシングル・パターン](../Web-single-pattern/design_ja.md)よりも構成は複雑になりますが、前処理・推論パターンでは効率的なリソース活用や個別開発、障害分離が可能になります。特にディープ・ラーニングを推論器に使用するアーキテクチャでは、前処理・推論パターンになることが多いです。
10 | `Diagram2`のように前段にプロキシを配置して、前処理と推論をマイクロサービス化するパターンも可能です。その場合、プロキシを仲介させてデータ取得、前処理、推論を分割した構成になります。こうすることによって、データ取得サーバ、前処理サーバ、推論サーバを独立したライブラリやコードベース、リソースで開発することができます。ただしコンポーネントが増えるぶん、コードベースやバージョン管理、障害対応が難しくなります。 11 | 12 | ## Diagram 13 | ### Simple prep-pred pattern 14 | ![diagram1](diagram1.png) 15 | 16 | ### Microservice prep-pred pattern 17 | ![diagram2](diagram2.png) 18 | 19 | ## Pros 20 | - 前処理と推論でサーバやコードベースを分割することで、リソース効率化や障害分離が可能。 21 | - リソースの増減を柔軟に実装することができる。 22 | - 使用するライブラリのバージョンを前処理と推論で独立して選択することが可能。 23 | 24 | ## Cons 25 | - 管理対象のサーバやネットワーク構成が複雑になるため、運用負荷増加。 26 | - 前処理器・推論器間のネットワークがボトルネックになることがある。 27 | 28 | ## Needs consideration 29 | - 前処理モデルと推論モデルで独立して学習することはできないため、前処理と推論のパラメータを一致させる必要がある。 30 | - 前処理モデルと推論モデルで独立して学習している場合、システムとしては障害にならないことが多いが、推論結果が想定外になることがある。 31 | - 前処理器と推論器のリソースを個別にチューニングすることが必要。 32 | 33 | ## Sample 34 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/prep_pred_pattern 35 | -------------------------------------------------------------------------------- /Serving-patterns/Prep-pred-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Preprocess-prediction pattern 2 | 3 | ## Usecase 4 | - 전처리 및 예측에서 사용하는 코드가 다른 경우, 라이브러리나 리소스의 요구 사항(requirements)가 있는 경우. 5 | - 리소스의 이슈를 나누고 가용성을 향상시키기 위해 전처리와 예측을 분리하고 싶은 경우. 6 | 7 | ## Architecture 8 | 전처리 요구 사항과 예측 요구 사항이 다른 경우가 있습니다. 보통 전처리는 숫자 데이터의 normalization, standardization, 범주형 데이터의 one-hot encoding, NLP의 vocab filtering, 이미지 크기 조정 등을 실행하며, 프리트레인(pretained)될 수도 있고 룰 베이스로 실행될 수도 있습니다. 반면에, 예측은 예측을 반환하기 위해 입력을 받을 수 있는 프리트레인된 빌드나 바이너리화된 모델 파일이 필요합니다. 전처리는 Python으로 작성된 반면, 예측은 Tensorflow나 ONNX로 바이너리로 빌드하는 경우도 있습니다. 이러한 경우, 별도의 서버 또는 컨테이너를 구축해 각 리소스의 개발 및 운영을 최적화할 수 있습니다.
9 | 전처리와 예측 모델을 별도의 리소스로 나누기 때문에 리소스에 대한 튜닝, 네트워크 연결, 버전화를 각각 고려해야 합니다. 이는 시스템을 [web single pattern](../Web-single-pattern/design_ko.md)보다 복잡하게 만드는 반면, 전처리-예측 패턴은 서빙 리소스를 효율적으로 사용할 수 있고, 독립적인 개발과 장애 격리(fault isolation)를 가능하게 합니다. 예측을 위해 딥러닝을 사용하는 경우 이 패턴을 적용하는 경우가 많습니다.
10 | `diagram2`는 전처리와 예측 앞에 프록시를 배치해 마이크로서비스로 만드는 모습을 보여줍니다. 이 경우 프록시는 데이터 검색, 전처리 및 예측 서비스를 중재합니다. 이 기능을 통해 독립적인 라이브러리, 언어 및 인프라를 별도로 개발할 수 있습니다. 그러나 장애 발생 시 문제 해결을 위해 모든 구성요소를 이해하는 관리 구성요소를 추가해야 합니다. 11 | 12 | ## Diagram 13 | ### Simple prep-pred pattern 14 | ![diagram1](diagram1.png) 15 | 16 | ### Microservice prep-pred pattern 17 | ![diagram2](diagram2.png) 18 | 19 | ## Pros 20 | - 장애 격리로 리소스를 효율적으로 사용할 수 있습니다. 21 | - 리소스 사용의 유연성 및 확장성. 22 | - 구성 요소별 라이브러리 및 언어 버전 선택 가능합니다. 23 | 24 | ## Cons 25 | - 리소스 복잡성으로 운영 비용이 증가합니다. 26 | - 전처리와 예측 사이의 네트워크 연결이 병목이 될 수 있습니다. 27 | 28 | ## Needs consideration 29 | - 전처리, 예측 등 모델 전체를 독자적으로 학습하는 것은 불가능하기 때문에 여전히 한 번의 학습에서 파라미터를 조정해야 합니다. 30 | - 전처리 및 예측을 별도로 개발하면, 예측이 부정확할 수 있지만, 시스템으로서 문제가 발생하지 않을 수 있습니다. 31 | - 리소스를 각각 따로 관리해야 합니다. 32 | 33 | ## Sample 34 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/prep_pred_pattern 35 | -------------------------------------------------------------------------------- /Serving-patterns/Prep-pred-pattern/diagram1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Prep-pred-pattern/diagram1.png -------------------------------------------------------------------------------- /Serving-patterns/Prep-pred-pattern/diagram2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Prep-pred-pattern/diagram2.png -------------------------------------------------------------------------------- /Serving-patterns/README.md: -------------------------------------------------------------------------------- 1 | # Serving patterns 2 | 3 | - [Web single pattern](./Web-single-pattern/design_en.md) 4 | 5 | 6 | - [Synchronous pattern](./Synchronous-pattern/design_en.md) 7 | 8 | 9 | - [Asynchronous pattern](./Asynchronous-pattern/design_en.md) 10 | 11 | 12 | - [Batch pattern](./Batch-pattern/design_en.md) 13 | 14 | 15 | - [Prep-pred pattern](./Prep-pred-pattern/design_en.md) 16 | 17 | 18 | - [Microservice vertical pattern](./Microservice-vertical-pattern/design_en.md) 19 | 20 | 21 | - [Microservice horizontal pattern](./Microservice-horizontal-pattern/design_en.md) 22 | 23 | 24 | - [Prediction cache pattern](./Prediction-cache-pattern/design_en.md) 25 | 26 | 27 | - [Data cache pattern](./Data-cache-pattern/design_en.md) 28 | 29 | 30 | - [Prediction circuit break pattern](./Prediction-circuit-break-pattern/design_en.md) 31 | 32 | 33 | - [Multiple stage prediction pattern](./Multiple-stage-prediction-pattern/design_en.md) 34 | 35 | - [Serving template pattern](./Serving-template-pattern/design_en.md) 36 | 37 | - Edge prediction pattern: To do 38 | 39 | - [Antipatterns](./Anti-patterns/README.md) 40 | 41 | - [Online bigsize pattern](./Anti-patterns/Online-bigsize-pattern/design_en.md) 42 | 43 | - [All-in-one pattern](./Anti-patterns/All-in-one-pattern/design_en.md) -------------------------------------------------------------------------------- /Serving-patterns/README_ja.md: -------------------------------------------------------------------------------- 1 | # Serving patterns 2 | 3 | 4 | - [Web single pattern](./Web-single-pattern/design_ja.md) 5 | 6 | 7 | - [Synchronous pattern](./Synchronous-pattern/design_ja.md) 8 | 9 | 10 | - [Asynchronous pattern](./Asynchronous-pattern/design_ja.md) 11 | 12 | 13 | - [Batch pattern](./Batch-pattern/design_ja.md) 14 | 15 | 16 | - [Prep-pred pattern](./Prep-pred-pattern/design_ja.md) 17 | 18 | 19 | - [Microservice vertical pattern](./Microservice-vertical-pattern/design_ja.md) 20 | 21 | 22 | - [Microservice horizontal pattern](./Microservice-horizontal-pattern/design_ja.md) 23 | 24 | 25 | - [Prediction cache pattern](./Prediction-cache-pattern/design_ja.md) 26 | 27 | 28 | - [Data cache pattern](./Data-cache-pattern/design_ja.md) 29 | 30 | 31 | - [Prediction circuit break pattern](./Prediction-circuit-break-pattern/design_ja.md) 32 | 33 | 34 | - [Multiple stage prediction pattern](./Multiple-stage-prediction-pattern/design_ja.md) 35 | 36 | - [Serving template pattern](./Serving-template-pattern/design_ja.md) 37 | 38 | - Edge prediction pattern: To do 39 | 40 | 41 | - [Antipatterns](./Anti-patterns/README_ja.md) 42 | 43 | - [Online bigsize pattern](./Anti-patterns/Online-bigsize-pattern/design_ja.md) 44 | 45 | - [All-in-one pattern](./Anti-patterns/All-in-one-pattern/design_ja.md) -------------------------------------------------------------------------------- /Serving-patterns/README_ko.md: -------------------------------------------------------------------------------- 1 | # Serving patterns 2 | 3 | - [Web single pattern](./Web-single-pattern/design_ko.md) 4 | 5 | 6 | - [Synchronous pattern](./Synchronous-pattern/design_ko.md) 7 | 8 | 9 | - [Asynchronous pattern](./Asynchronous-pattern/design_ko.md) 10 | 11 | 12 | - [Batch pattern](./Batch-pattern/design_ko.md) 13 | 14 | 15 | - [Prep-pred pattern](./Prep-pred-pattern/design_ko.md) 16 | 17 | 18 | - [Microservice vertical pattern](./Microservice-vertical-pattern/design_ko.md) 19 | 20 | 21 | - [Microservice horizontal pattern](./Microservice-horizontal-pattern/design_ko.md) 22 | 23 | 24 | - [Prediction cache pattern](./Prediction-cache-pattern/design_ko.md) 25 | 26 | 27 | - [Data cache pattern](./Data-cache-pattern/design_ko.md) 28 | 29 | 30 | - [Prediction circuit break pattern](./Prediction-circuit-break-pattern/design_ko.md) 31 | 32 | 33 | - [Multiple stage prediction pattern](./Multiple-stage-prediction-pattern/design_ko.md) 34 | 35 | - [Serving template pattern](./Serving-template-pattern/design_ko.md) 36 | 37 | - Edge prediction pattern: To do 38 | 39 | - [Antipatterns](./Anti-patterns/README_ko.md) 40 | 41 | - [Online bigsize pattern](./Anti-patterns/Online-bigsize-pattern/design_ko.md) 42 | 43 | - [All-in-one pattern](./Anti-patterns/All-in-one-pattern/design_ko.md) 44 | -------------------------------------------------------------------------------- /Serving-patterns/Serving-template-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Serving template pattern 2 | 3 | ## Usecase 4 | - When you need to develop and release a tons of prediction serving with same input and output with common interface 5 | - When you can standardize components in serving except for a prediction smodel 6 | 7 | ## Architecture 8 | The prediction template pattern is to standardize prediction codebase, infrastructure and deployment policy as a reusable template. By standardizing the serving set, you gain profit of efficiency in development as well as release, and ability to share knowledge between multiple servings. When you are developing a system with multiple machine learning prediction models running, the team's productivity may get decreased if each serving has different architecture. It may happen if all the models take a separate interface, library, OS, and chipset, which is quite unusual, but if you can commonize (e.g. same Python3.x, Ubuntu18.0x, x86_64 architecture CPU, Nginx proxy, REST server with FastAPI, and scikit-learn and Keras models), making a reusable template is a good choise. In addition, by making interface for calling preprocess and prediction in common, you may be able to make an ideal template that just converting model file becomes a prediction server.
9 | The pattern enables standardizing common components and reusable. Its ideal template is the one that just by changing the model-specific paramenter in JSON or YAML to release the model. Even if you cannot make it standardized that far, you may try to standardize codebases other than model-specific preprocess and prediction to reduce the amount of coding. In addition, it is possible to commonize infrastructure layer, including monitoring, alert, logging, authorization, authentication and security. Even though it is probably difficult to provide a company-wide common template, you may consider step-by-step standardization; e.g. standardize infrastructure for company-wide, non-machine learning middleware for a team, and other components except for a model within a project.
10 | Note that you need consider template version update policy for the production servings. It is necessary to develop a template with backward compatibility. You may update the servings based on your service level. You may try updating the batch server in a timeframe the batch is not running. You may use the [online AB test pattern](../../QA-patterns/Online-ab-test-pattern/design_en.md) to update online services, such as REST server. If you cannot keep the backward compatibility, you may need to run the whole integration test before releasing to production.
11 | The last section lists step-by-step template level from infrastructure layer to machine learning model specific. 12 | 13 | - Infrastructure: you may standardize without much consent on machine learning model, if the model require a specific chipset or runtime. 14 | - OS 15 | - network 16 | - authentication and authorization 17 | - security 18 | - logging 19 | - monitoring and alert 20 | - Non-machine learning middleware and library: you may standardize with some consideration to ML model. 21 | - web server and job management server 22 | - logger library 23 | - REST server library and Protocol buffer with GRPC 24 | - Machine learning library and language: require consideration. 25 | - language version 26 | - library version 27 | - interface 28 | - input and output 29 | 30 | ## Diagram 31 | ![diagram](diagram.png) 32 | 33 | 34 | ## Pros 35 | - Able to improve efficiency 36 | - Manage by a common policy 37 | 38 | ## Cons 39 | - Updating the template require consideration and backward compatibility 40 | 41 | ## Needs consideration 42 | - Backward compatibility and update policy 43 | - Integration test 44 | 45 | ## Sample 46 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/template_pattern -------------------------------------------------------------------------------- /Serving-patterns/Serving-template-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Serving template pattern 2 | 3 | ## Usecase 4 | - 同一入出力の推論器を大量に開発、リリースする場合 5 | - 推論器のうち、モデル以外を共通化することができる場合 6 | 7 | ## Architecture 8 | 推論テンプレート・パターンは推論器のコードやインフラ構成、デプロイ方針を共通化し、再利用可能なテンプレートを用意するパターンです。推論器の方式を共通化することによって、推論器開発およびリリースを効率化すると同時に、システム理解やトラブルシューティングのノウハウを応用することが可能になります。機械学習モデルによる推論を大量に組み込んだシステムを開発する場合、入出力インターフェイスや推論モデルの呼び出し等が各推論器で異なる構成だと、各推論器の開発効率が下がります。すべての機械学習モデルが異なった入出力とライブラリ、OS、チップセットを使用する必要があるのであれば致し方ないですが、そうでない場合(例えばほとんどのモデルがPython3.xを使ってUbuntu18.0x上でx86_64アーキテクチャでNginxプロキシを使い、FastAPIによるRESTサーバとして稼働し、モデルはScikit-learnとKerasを使用して開発している場合)、共通の開発・推論テンプレートを用意することで、開発者の環境構築が不要になります。更には前処理と推論モデルの呼び出し方、出力を共通化できれば、モデルを組み込むだけで推論機を稼働させられるテンプレートを用意できます。
9 | 推論テンプレート・パターンでは共通化可能な部品を共通化し、再利用可能にします。理想的にはモデル固有の箇所をJSONやYAMLのパラメータで設定するだけで推論器をリリースできる状態ですが、そこまで共通化できなくても、前処理と推論モデル呼び出し以外のPythonコード(ライブラリバージョン含む)を共通化できれば、開発者のコーディング量が大きく削減されるはずです。加えてインフラレイヤーとして監視通報やログ収集、認証認可等を共通化することも可能です。全推論器を網羅するテンプレートを作ることが難しいとしても、社内でインフラのみ共通化し、チーム内では機械学習に関わらないミドルウェアとライブラリをテンプレート化し、そしてプロジェクトでは機械学習モデル以外を共通化するという方針にすることで、開発効率を向上させることも可能です。
10 | 推論テンプレート・パターンを利用する際の注意点は、テンプレートのバージョンアップが必要な場合、稼働中のサービスのアップデート方針です。テンプレートの更新では基本的に後方互換性を保った更新が必要です。後方互換性が保たれているのであれば、各サービスのサービスレベルに応じて推論器の入れ替えを行います。バッチサーバであればバッチ稼働中以外に更新可能ですし、RESTサーバ等のオンラインサービスであれば、[オンラインABテスト・パターン](../../QA-patterns/Online-ab-test-pattern/design_ja.md)で徐々に入れ替えていく方針が考えられます。ただし、後方互換性を保てないテンプレート更新が必要になる場合は注意が必要で、場合によっては全推論器のインテグレーション・テストを再実行する必要があります。
11 | 最後に、インフラ含めた機械学習モデル固有要件のテンプレート化レベルを以下に示します。 12 | 13 | - インフラ(機械学習モデルに依らず共通化可能。ただし、モデルが特定のチップセットやランタイムが必要な場合はこの限りではない) 14 | - OS 15 | - ネットワーク 16 | - 認証認可 17 | - セキュリティ 18 | - ログ収集 19 | - 監視通報 20 | - 非機械学習のミドルウェアやライブラリ(多くの場合機械学習モデルに依らず共通化可能) 21 | - Webサーバやジョブ管理サーバ 22 | - ロガーライブラリ 23 | - RESTサーバライブラリやProtocol bufferとGRPC 24 | - 機械学習モデルを稼働させるためのプログラミング言語やライブラリ(機械学習モデル固有になる場合あり) 25 | - プログラミング言語のバージョン 26 | - ライブラリのバージョン 27 | - 入出力インターフェイス 28 | - 入力データと出力データ 29 | 30 | ## Diagram 31 | ![diagram](diagram.png) 32 | 33 | 34 | ## Pros 35 | - 開発効率を向上させることができる。 36 | - 同一の運用方針で管理することができる。 37 | - 品質の良いテンプレートを作ればバグが混入する可能性も削減可能。 38 | 39 | ## Cons 40 | - テンプレートを更新する際には注意が必要。 41 | 42 | ## Needs consideration 43 | - テンプレートの後方互換性維持およびアップデート方針。 44 | - 後方互換性を保てない場合のインテグレーション・テスト方法。 45 | 46 | ## Sample 47 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/template_pattern -------------------------------------------------------------------------------- /Serving-patterns/Serving-template-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Serving template pattern 2 | 3 | ## Usecase 4 | - 공통 인터페이스로 동일한 입력과 출력을 사용하는 수많은 예측 서비스를 개발 및 배포해야 하는 경우. 5 | - 서빙 구성요소 중 예측 모델을 제외하고 모듈화할 수 있는 경우. 6 | 7 | ## Architecture 8 | Serving template pattern은 예측 서비스의 코드나 인프라 구성, 배포 방식을 모듈화하고 재사용 가능한 템플릿으로 준비하는 패턴입니다. 예측 서비스의 방식을 모듈화 하면 개발 효율성 및 배포, 여러 서빙 간에 지식 공유 등의 이점을 얻을 수 있습니다. 여러 머신러닝 예측 모델이 실행되는 시스템을 개발할 때, 서빙 모델이 각각 다른 아키텍처를 가지면 팀의 생산성이 저하될 수 있습니다. 모든 모델들이 각각의 인터페이스, 라이브러리, OS, 칩셋을 사용하는 경우 이 문제가 발생할 수 있지만 공통화할 수 있는 경우(예를 들어 파이썬 3.x, 우분투 18점대, x84_64 CPU, Nginx 프록시, Rest 서버, scikit-learn, Keras 등) 이런 요소를 재사용 가능한 템플릿으로 만드는 것은 좋은 방법입니다. 추가로, 전처리와 예측을 호출하기 위한 인터페이스를 공통으로 만들면 모델 파일을 예측 서버로 변경하는 것만으로 예측 서버가 되는 이상적인 템플릿을 만들 수 있습니다.
9 | 10 | 11 | 이 패턴을 사용하면 공통 구성 요소를 모듈화하고 재사용할 수 있습니다. JSON 또는 YAML 파일에서 모델별 파라미터를 변경해 모델을 배포하는 것이 이상적인 템플릿입니다. 이렇게 표준화할 수 없는 경우에도 모델별 전처리 및 예측 외의 코드를 모듈화해 코드 양을 줄일 수 있습니다. 또한 모니터링, 경고, 로깅, 권한 부여, 인증 및 보안을 포함한 인프라 계층을 표준화할 수 있습니다. 회사 전체의 공통 템플릿을 제공하는 것은 어려울 수 있지만, 단계별 표준화를 고려할 수 있습니다. 예를 들어, 팀을 위한 전사적 비머신러닝 미들웨어 및 프로젝트 내 모델을 제외한 기타 구성 요소에 대한 인프라를 표준화할 수 있습니다.
12 | 13 | 14 | 프러덕션 서빙용 템플릿 버전 업데이트 정책을 고려해야 합니다. 이전 버전과 호환성을 갖춘 템플릿을 개발해야 합니다. 서비스 수준에 따라 서빙을 업데이트할 수 있습니다. 배치가 실행되지 않는 시간대에 배치 서버를 업데이트할 수 있습니다. [Online AB test pattern](../../QA-patterns/Online-ab-test-pattern/design_ko.md)을 사용해 REST 서버와 같은 온라인 서비스를 업데이트할 수 있습니다. 이전 버전과 호환성을 유지할 수 없는 경우 프러덕션으로 출시하기 전에 전체 통합 테스트를 실행해야 할 수 있습니다.
15 | 16 | 아래에는 인프라 계층에서 머신러닝 모델에 이르기까지 단계별 템플릿 레벨이 나열되어 있습니다. 17 | 18 | - 인프라 : 특정 칩셋이나 런타임이 필요한 경우 머신러닝 모델과 상관없이 표준화할 수 있습니다. 19 | - OS 20 | - 네트워크 21 | - 인증 및 권한 부여 22 | - 보안 23 | - 로깅 24 | - 모니터링 및 경고 25 | - 비머신러닝 미들웨어나 라이브러리 : 머신러닝 모델을 고려해 표준화할 수 있습니다. 26 | - 웹 서버 및 작업 관리 서버 27 | - 로깅 라이브러리 28 | - REST 서버 라이브러리와 GRPC를 사용한 프로토콜 버퍼 29 | - 머신러닝 라이브러리와 언어 : 심사숙고가 필요합니다. 30 | - 언어 버전 31 | - 라이브러리 버전 32 | - 인터페이스 33 | - 입력과 출력 34 | 35 | ## Diagram 36 | ![diagram](diagram.png) 37 | 38 | 39 | ## Pros 40 | - 효율성을 개선할 수 있습니다. 41 | - 공통 정책으로 관리합니다. 42 | 43 | 44 | ## Cons 45 | - 템플릿을 업데이트하려면 심사숙고와 이전 버전과의 호환성이 필요합니다. 46 | 47 | 48 | ## Needs consideration 49 | - 이전 버전과 호환성 및 업데이트 정책 50 | - 통합 테스트 51 | 52 | ## Sample 53 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/template_pattern -------------------------------------------------------------------------------- /Serving-patterns/Serving-template-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Serving-template-pattern/diagram.png -------------------------------------------------------------------------------- /Serving-patterns/Synchronous-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Synchronous pattern 2 | 3 | ## Usecase 4 | - When in your business logic, the model inference is a blocker to proceed to the next step. 5 | - When your workflow depends on the inference result. 6 | 7 | ## Architecture 8 | The synchronous pattern is used to run prediction synchronously. It blocks the workflow until the prediction finishes. If you develop the inference server with REST or GRPC, it often becomes the synchronous pattern. This is one of the easiest patterns to use, as its workflow can be visualized in a simple step-by-step fashion. 9 | 10 | ## Diagram 11 | ![diagram](diagram.png) 12 | 13 | ## Pros 14 | - Easy to manage with its simplicity. All operational aspects like transaction tracing, monitoring etc become easy as well. 15 | - Service workflow becomes simple for the process won't proceed until the prediction completes. 16 | 17 | ## Cons 18 | - The prediction latency can become a performance bottleneck. 19 | - You might have to consider a workaround for not degrading your user experience because of prediction latency. 20 | - If the client of your service is another service then this pattern leads to blocked threads on the client side. 21 | 22 | ## Needs consideration 23 | - Work around for not making user experience getting worse for prediction latency. 24 | - Needs timeout if the latency is too long. 25 | 26 | ## Sample 27 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/synchronous_pattern 28 | -------------------------------------------------------------------------------- /Serving-patterns/Synchronous-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Synchronous pattern 2 | 3 | ## Usecase 4 | - アプリケーションのワークフローとして、推論結果が出るまで次に進めない仕様のとき 5 | - ワークフローが推論結果に依存するとき 6 | 7 | ## Architecture 8 | 同期パターンは機械学習の推論を同期的に処理するパターンです。クライアントは推論のリクエストに対してレスポンスが得られるまで待機します。機械学習の推論サーバをRESTまたはGRPCで構成した場合、同期パターンになることが多いです。推論含めたワークフローを考えやすいため、同期パターンは実装・運用しやすいアーキテクチャになります。 9 | 10 | ## Diagram 11 | ![diagram](diagram.png) 12 | 13 | ## Pros 14 | - シンプルな構成で運用しやすい。 15 | - 推論が完了するまでクライアントは次の処理に移行しないため、ワークフローを考えやすい。 16 | 17 | ## Cons 18 | - 推論がパフォーマンスのボトルネックになりやすい。 19 | - 推論の待機時間が発生するため、その間にユーザ体験を低下させない方法を考慮する必要がある。 20 | 21 | ## Needs consideration 22 | - 推論の待機時間に対するユーザ体験の低下防止。 23 | - 待機時間が長い場合はクライアントからタイムアウトすることが必要になる場合もある。 24 | 25 | ## Sample 26 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/synchronous_pattern 27 | -------------------------------------------------------------------------------- /Serving-patterns/Synchronous-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Synchronous pattern 2 | 3 | ## Usecase 4 | - 다음 단계를 진행하기 위해 예측의 결과를 받아야 하는 경우. 5 | - 예측 결과에 따라 워크플로우가 달라지는 경우. 6 | 7 | ## Architecture 8 | Synchronous pattern은 예측을 동기식으로 실행할 때 사용됩니다. 예측이 끝날 때까지 프로세스를 블락합니다. REST 또는 GRPC를 사용해 예측 서버를 개발하면 종종 동기 패턴이 됩니다. 간단한 단계별 워크플로우를 고려할 수 있는 가장 쉬운 패턴 중 하나입니다. 9 | 10 | ## Diagram 11 | ![diagram](diagram.png) 12 | 13 | ## Pros 14 | - 아키텍처의 단순함으로 관리가 쉽습니다. 15 | - 예측이 완료될 때까지 프로세스가 진행되지 않아서 서비스 워크플로우가 단순해집니다. 16 | 17 | ## Cons 18 | - 예측 속도가 병목현상이 됩니다. 19 | - 예측 지연으로 인해 사용자 경험이 악화되지 않도록 해결방법을 고려해야 합니다. 20 | 21 | ## Needs consideration 22 | - 예측 대기 시간으로 인해 사용자 경험이 악화되지 않도록 노력해야 합니다. 23 | - 대기 시간이 너무 길면 타임아웃이 필요합니다. 24 | 25 | ## Sample 26 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/synchronous_pattern 27 | -------------------------------------------------------------------------------- /Serving-patterns/Synchronous-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Synchronous-pattern/diagram.png -------------------------------------------------------------------------------- /Serving-patterns/Web-single-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Web single pattern 2 | 3 | ## Usecase 4 | - When you want to quickly release the predictor in the simplest architecture. 5 | 6 | ## Architecture 7 | The web single pattern is an architecture that packs all the artifacts and code for the prediction model in a web server. Since the single server REST (or GRPC) interface, preprocess, and trained model are in one place, you can create and deploy them as a simple predictor.
8 | If you want to deploy multiple replicas, you need to deploy them behind a load balancer or proxy. In case you are using GRPC for the interface, you need to consider client side load balancing or layer-7 load balancer.
9 | To build your model into a web server, you can adopt either [model-in-image pattern](./../../Operation-patterns/Model-in-image-pattern/design_en.md) or [model-load pattern](./../../Operation-patterns/Model-load-pattern/design_en.md). 10 | 11 | ## Diagram 12 | ![diagram](diagram.png) 13 | 14 | ## Pros 15 | - Able to use one programming language, such as Python, for the web server, preprocess and inference. 16 | - Easy to manage because of it's simplicity. 17 | - Easier troubleshooting. 18 | - Minimal time-to-productionize post model training. 19 | - It is usually suggested to start your production architecture with deploying your models in the web single pattern in a synchronous fashion. 20 | 21 | ## Cons 22 | - Since all components are packed in a server or a docker image, applying a small patch will require updating the whole image 23 | - Updates will also require a service deployment, which in bigger organizations requires one to follow a hefty SDLC 24 | 25 | ## Needs consideration 26 | - Update and maintenance procedure for each component. 27 | - Scale change management of the web server. 28 | 29 | ## Sample 30 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/web_single_pattern 31 | -------------------------------------------------------------------------------- /Serving-patterns/Web-single-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Web single pattern 2 | 3 | ## Usecase 4 | - もっともシンプルな構成で推論器を素早くリリースしたいとき 5 | 6 | ## Architecture 7 | Webシングル・パターンはWebサーバにモデルを同梱させるパターンです。同一サーバにRESTインターフェイス(もしくはGRPC)と前処理、学習済みモデルをインストールすることによって、シンプルな機械学習推論器をつくることができます。
8 | 複数台のWebサーバで運用する場合はロードバランサーを導入して負荷分散することができます。ただしインターフェイスをGRPCで実装する場合、クライアントロードバランサーを用意するか、L7ロードバランサーを使用する必要があります。
9 | Webシングル・パターンへのモデルの含め方は[モデル・イン・イメージ・パターン](../../Operation-patterns/Model-in-image-pattern/design_ja.md)、[モデル・ロード・パターン](../../Operation-patterns/Model-load-pattern/design_ja.md)のいずれも実現可能です。 10 | 11 | ## Diagram 12 | ![diagram](diagram.png) 13 | 14 | ## Pros 15 | - Python等、同一プログラミング言語でWeb、前処理、推論を実装することが可能。 16 | - シンプルな構成で運用が簡単。 17 | - 障害発生時のトラブルシューティングが容易。 18 | - 1モデルで同期的に推論を返すだけであればWebシングル・パターンを推奨。 19 | 20 | ## Cons 21 | - REST実装や前処理が同一サーバやDocker imageに封入されるため、個別のコンポーネントを更新することができない。 22 | 23 | ## Needs consideration 24 | - REST実装や前処理、モデルを変更する際の更新方針。 25 | - 負荷増加時のWebサーバのスケール増減方法。 26 | 27 | ## Sample 28 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/web_single_pattern 29 | -------------------------------------------------------------------------------- /Serving-patterns/Web-single-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Web single pattern 2 | 3 | ## Usecase 4 | - 가장 간단한 아키텍처에서 예측 서버를 빠르게 출시하고 싶은 경우. 5 | 6 | ## Architecture 7 | Web single pattern은 예측 모델을 위한 모든 아티팩트를 웹 서버에 함께 저장하는 구조입니다. 단일 서버 REST(또는 GRPC) 인터페이스, 전처리, 훈련된 모델을 한 곳에서 사용하기 때문에 예측 서버를 간단히 생성하고 배포할 수 있습니다.
8 | 만약 여러 복제본을 배포하려면, 로드 밸런서나 프록시를 사용해 배포할 수 있습니다. 인터페이스에 GRPC를 사용하는 경우, 클라이언트측 로드 밸런싱 또는 L7 로드 밸런서를 고려해야 합니다.
9 | 웹 서버에 모델을 빌드하려면, [Model-in-image pattern](./../../Operation-patterns/Model-in-image-pattern/design_ko.md) 또는 [Model-load pattern](./../../Operation-patterns/Model-load-pattern/design_ko.md) 중 하나를 적용할 수 있습니다. 10 | 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | ## Pros 16 | - 웹 서버, 전처리, 예측할 때 파이썬 같은 하나의 프로그래밍 언어를 사용할 수 있습니다. 17 | - 아키텍처의 단순함으로 관리가 쉽습니다. 18 | - 트러블슈팅은 복잡하지 않습니다. 19 | - 동기식 시스템에서 모델을 배포하기 위해 웹 단일 패턴으로 시작할 것을 제안합니다. 20 | 21 | ## Cons 22 | - 모든 구성요소가 서버 또는 도커 이미지에 저장되므로 작은 패치를 적용하려면 전체 업데이트가 필요합니다. 23 | 24 | ## Needs consideration 25 | - 각 구성 요소의 업데이트 및 유지보수 절차 26 | - 웹 서버의 규모 변경 관리 27 | 28 | ## Sample 29 | https://github.com/shibuiwilliam/ml-system-in-actions/tree/main/chapter4_serving_patterns/web_single_pattern 30 | -------------------------------------------------------------------------------- /Serving-patterns/Web-single-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Serving-patterns/Web-single-pattern/diagram.png -------------------------------------------------------------------------------- /Training-patterns/Anti-patterns/Only-me-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Only-me pattern 2 | 3 | ## Case 4 | - Condition when a ML engineer completes his/her task, including coding, data retrieval, model development, and evaluation, that others cannot review or reproduce the ML engineer's job. 5 | - A ML engineer only provides a model without code and dataset, that nobody can run or evaluate it. 6 | 7 | ## Situation 8 | It is common to develop a machine learning model using Jupyter Notebook in a private laptop. In order to deploy the model into a production system, you need to make an environment aligned with the development environment, including code, data and versionings of OS, language and libraries. If you can't, you may not be able to reproduce performance just as the dev. Also, there are libraries that have no compatibility among versions that just a minor version change may corrupt model execution, or change in performance. To avoid these cases, the ML engineers should share the development environment to the other engineers.
9 | In the only-me pattern, the ML engineer completes his/her tasks in the private environment that are dependent on it. To run the model in the production, it is necessary to reproduce the ML engineer's laptop. It makes a situation where it is needed to dump the environemnt configurations, which may get easily changed with an update.
10 | You need to develop application to be deployed to the production. An application or backend engineers can develop UI and API, though the ML portion, including data retrieval, preprocess and postprocess, require development or support of the ML engineer. To release to the production, it is recommended to have architecture and code review within the team. 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - ML engineer can develop in his/her favorite environment. 18 | 19 | ## Cons 20 | - Difficult to reproduce model execution and release to production. 21 | 22 | ## Work around 23 | - Have a common set of versions for OS, language and library among model development and production environment. 24 | - Use of Docker or shared platform. 25 | - Use of repository and code review. 26 | 27 | ## Related design pattern 28 | - [Batch training pattern](./../../Batch-training-pattern/design_ja.md) 29 | - [Pipeline training pattern](./../../Pipeline-training-pattern/design_ja.md) -------------------------------------------------------------------------------- /Training-patterns/Anti-patterns/Only-me-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Only-me pattern 2 | 3 | ## Case 4 | - MLエンジニアが個人環境で開発し、開発プログラム、データセット、モデル、評価を他者がレビュー、再現できない状態。 5 | - MLエンジニアが個人環境で開発したモデルのみを提供し、正常な実行方法や評価方法が不明な状態。 6 | 7 | ## Situation 8 | モデルを個人LaptopのJupyter Notebookで開発するケースは多いです。モデルを本番システムに組み込むためにはモデル開発に使用したコードやデータ、環境(OSのバージョン、言語のバージョン、依存ライブラリのバージョン…)を開発環境同様に構築する必要があります。同じ環境でないと開発時同様のパフォーマンスを出せない可能性があるからです。ライブラリによってはバージョン間互換性が担保されず、マイナーバージョンが違うだけで実行できなくなる(または実行できるけどパフォーマンスが変わる)場合があります。そうした状況を避けるためには、モデル開発環境をMLエンジニア以外のエンジニア(ビルドエンジニア、アプリエンジニア、バックエンドエンジニア、SRE等々)に共有する必要があります。
9 | オンリー・ミー・パターンでは全てのモデル開発をMLエンジニアの個人環境で実施し、個人環境に完全に依存したモデルが完成します。完成したモデルを本番環境で正常に稼働させるためには、MLエンジニアの個人環境を再現することになります。そのためにはMLエンジニアの言語やライブラリやバージョン等を入手し構築する必要がありますが、なにかの拍子に更新をかけてしまった場合、再現不可能になるリスクもあります。
10 | モデルを本番環境で稼働させるにはプログラムも必要です。UIやAPI等はアプリエンジニアやバックエンドエンジニアが開発可能ですが、MLモデルを稼働させるためのコードは、入力データや前処理、後処理の整合性を取るためにMLエンジニアの開発やサポートが必要になります。本番導入にあたって、モデルの受け入れ段階でコードレビューを行い、エンジニア間でモデルやシステムの実行ロジックを相互に理解すると良いでしょう。 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - MLエンジニアは自分の使いやすい環境で開発可能。 18 | 19 | ## Cons 20 | - モデルを本番環境で正常稼働させることが困難になる。 21 | 22 | ## Work around 23 | - モデル開発と本番システムで共通のOS、言語、ライブラリのバージョンを揃えて開発する。 24 | - Dockerや共通基盤を活用して開発する。 25 | - 開発プログラムをレポジトリで管理し、コードレビューを行う。 26 | 27 | ## Related design pattern 28 | - [Batch training pattern](./../../Batch-training-pattern/design_ja.md) 29 | - [Pipeline training pattern](./../../Pipeline-training-pattern/design_ja.md) -------------------------------------------------------------------------------- /Training-patterns/Anti-patterns/Only-me-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Only-me pattern 2 | 3 | ## Case 4 | - 코딩, 데이터 검색, 모델 개발, 평가 등 ML 엔지니어의 작업을 다른 사람들이 검토하거나 재현할 수 없는 경우. 5 | - ML 엔지니어가 코드와 데이터 세트 없이 모델만 제공하여, 아무도 실행하거나 평가할 수 없는 경우. 6 | 7 | ## Situation 8 | 개인 컴퓨터에서 주피터 노트북을 이용하여 머신러닝 모델을 개발하는 경우가 많습니다. 모델을 실제 운영 시스템에 배포하기 위해서는 모델 개발에 사용한 코드, 데이터, OS의 버전, 언어, 라이브러리 등 개발 환경과 맞게 구축해야 합니다. 그렇지 않다면, 개발할 때와 동일한 성능을 재현할 수 없을 수도 있습니다. 또, 사소한 라이브러리 버전 변경으로 모델 실행이나 성능에 영향을 줄 수도 있습니다. 이를 피하기 위하여 ML 엔지니어들은 개발환경을 다른 엔지니어들과 공유해야 합니다.
9 | Only-me pattern에서 모든 모델 개발은 ML 엔지니어의 개인 환경에서 실행되어 개인 환경에 완전히 의존한 모델로 완성됩니다. 완성된 모델을 실제 환경에서 정상적으로 가동하기 위해서는 ML 엔지니어의 개인 환경을 동일하게 재현해야 합니다. 이 경우, 어떠한 순간에 업데이트로 인해 환경 설정들이 변하여 모델 재현이 불가능해질 수 있는 리스크가 있습니다.
10 | 실제 환경에서 제대로 동작하는 어플리케이션을 개발하기 위해서는 협업이 필요합니다. UI와 API는 어플리케이션/백엔드 엔지니어가 개발하며, 데이터 검색, 전후 처리를 포함한 ML 부분은 ML 엔지니어가 개발 및 지원합니다. 실제 운영 환경으로 안전한 릴리즈하기 위하여, 모델을 적용하는 단계에서부터 코드 리뷰를 실시하고 엔지니어 간에 모델이나 시스템 실행 로직에 대하여 서로 이해하는 것이 좋습니다. 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - ML 엔지니어가 자신이 좋아하는 환경에서 개발할 수 있습니다. 18 | 19 | ## Cons 20 | - 실제 운영 환경에서 모델 실행 및 릴리즈 하기 어려움. 21 | 22 | ## Work around 23 | - 개발 환경과 실제 운영 시스템에서 사용할 공통의 OS, 언어, 라이브러리 버전. 24 | - Docker 혹은 공유되는 플랫폼 사용. 25 | - 레파지토리 사용과 코드 리뷰. 26 | 27 | ## Related design pattern 28 | - [Batch training pattern](./../../Batch-training-pattern/design_ko.md) 29 | - [Pipeline training pattern](./../../Pipeline-training-pattern/design_ko.md) 30 | -------------------------------------------------------------------------------- /Training-patterns/Anti-patterns/Only-me-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Training-patterns/Anti-patterns/Only-me-pattern/diagram.png -------------------------------------------------------------------------------- /Training-patterns/Anti-patterns/README.md: -------------------------------------------------------------------------------- 1 | # Training Antipatterns 2 | 3 | - [Only-me pattern](./Only-me-pattern/design_en.md) 4 | 5 | - [Training code in serving pattern](./Training-code-in-serving-pattern/design_en.md) 6 | 7 | - [Too many pipes pattern](./Too-many-pipes-pattern/design_en.md) -------------------------------------------------------------------------------- /Training-patterns/Anti-patterns/README_ja.md: -------------------------------------------------------------------------------- 1 | # Training Antipatterns 2 | 3 | - [Only-me pattern](./Only-me-pattern/design_ja.md) 4 | 5 | - [Training code in serving pattern](./Training-code-in-serving-pattern/design_ja.md) 6 | 7 | - [Too many pipes pattern](./Too-many-pipes-pattern/design_ja.md) -------------------------------------------------------------------------------- /Training-patterns/Anti-patterns/README_ko.md: -------------------------------------------------------------------------------- 1 | # Training Antipatterns 2 | 3 | - [Only-me pattern](./Only-me-pattern/design_ko.md) 4 | 5 | - [Training code in serving pattern](./Training-code-in-serving-pattern/design_ko.md) 6 | 7 | - [Too many pipes pattern](./Too-many-pipes-pattern/design_ko.md) -------------------------------------------------------------------------------- /Training-patterns/Anti-patterns/Too-many-pipes-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Too many pipes pattern 2 | 3 | ## Case 4 | - Too many routes in one training pipeline in complex state. 5 | - Many data sources and access objects with less common abstract method. 6 | 7 | ## Situation 8 | A machine learning's training pipeline will not only do training, but also model tuning, experiment and evaluation. If you want to have various parameter tunings and experiments parallelly, the pipeline will be not one-way straightforward. If you have dependencies among pipeline jobs, its complexity increases. To maintain the pipeline, you may need SRE for the training platform to deal with errors and troubleshooting. When you make the training platform as one of internal systems to be maintained, it is suggested to make the pipeline as simple as possible to isolate fault and increate usability.
9 | Another reason that makes a pipeline complex is various data sources and access methods. If your data is stored in a number of DWH (RDB, NoSQL, NAS, Web API, cloud storage, Hadoop, multiregional, and so on), defining access, authentication and authorization to each of them will be a mess. It is recommended to use a common library to manage data access object, though spreading data to multiple warehouses will give a data engineer hard time and unhealthiness. It is always better to choose appropriate and limited number of DWH. 10 | 11 | ## Diagram 12 | ![diagram](diagram.png) 13 | 14 | 15 | ## Pros 16 | - Able to run various jobs with complex pipelines. 17 | 18 | ## Cons 19 | - Difficult to maintain and understand. 20 | 21 | ## Work around 22 | - Good to have dependency management when defining pipeline. 23 | - Always organize data 24 | 25 | ## Related design pattern 26 | - [Batch training pattern](./../../Batch-training-pattern/design_en.md) 27 | - [Pipeline training pattern](./../../Pipeline-training-pattern/design_en.md) -------------------------------------------------------------------------------- /Training-patterns/Anti-patterns/Too-many-pipes-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Too many pipes pattern 2 | 3 | ## Case 4 | - 一つの目的や学習のための学習パイプラインが多様且つ複雑な状態。 5 | - データの取得元が多様且つ取得方法が適度に抽象化されていない状態。 6 | 7 | ## Situation 8 | 機械学習の学習パイプラインでは、学習だけでなくモデルのチューニングや実験、評価を行います。多様なパラメータチューニングや実験を同時並行で実行する場合、パイプラインも一本道ではなく多岐に渡るものになるでしょう。パイプライン内のジョブ間の依存関係がある場合は更に複雑化します。パイプラインがエラーで停止した場合の障害対応が発生し、パイプライン運用のためのSREが必要になるでしょう。社内システム基盤運用の一環として考えるならば機械学習の学習基盤運用は必須ですが、エラー箇所を局所化する、またはユーザビリティを向上させるために、パイプラインをシンプルに留めることは重要です。
9 | 学習パイプラインを複雑化するもう一つの要因はデータアクセス方法が多様であることです。学習に使うデータが様々なDWH(RDB、NoSQL、NAS、Web API、クラウド、Hadoop、更には複数拠点等々)に格納されている場合、それらへのアクセス方法や認証認可は各々に定められています。各データ格納庫へのアクセスを抽象化するライブラリを使うことを推奨しますが、データが散らばっている状態はデータエンジニアの工数と健康に悪影響を与えるため、データを整理しておく(適切にDWHを選択する)ことが重要です。 10 | 11 | ## Diagram 12 | ![diagram](diagram.png) 13 | 14 | 15 | ## Pros 16 | - 複雑なパイプラインによって多様な処理を実行することができる。 17 | 18 | ## Cons 19 | - 運用が困難。 20 | 21 | ## Work around 22 | - ジョブ間の依存関係はパイプライン構築時に制御できると良い。 23 | - データは整理すること。 24 | 25 | ## Related design pattern 26 | - [Batch training pattern](./../../Batch-training-pattern/design_ja.md) 27 | - [Pipeline training pattern](./../../Pipeline-training-pattern/design_ja.md) -------------------------------------------------------------------------------- /Training-patterns/Anti-patterns/Too-many-pipes-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Too many pipes pattern 2 | 3 | ## Case 4 | - 학습 파이프라인이 너무 다양하고 복잡한 경우. 5 | - 데이터 소스가 너무 많고 가져오는 방법이 적절히 추상화되어있지 않은 경우. 6 | 7 | ## Situation 8 | 머신러닝의 학습 파이프라인은 학습뿐만 아니라 모델 튜닝, 실험, 평가에도 사용할 수 있습니다. 다양한 파라미터 튜닝과 실험을 병행하기 위해서는 파이프라인을 다양하게 사용될 수 있도록 만들어야 합니다. 만약 파이프라인 작업 간의 의존관계가 있다면 더욱 복잡해질 수 있습니다. 파이프라인의 에러 해결 및 트러블 슈팅과 같은 운영을 위해 SRE(Site Reliability Engineering)가 필요할 수도 있습니다. 따라서 학습 플랫폼을 내부 시스템으로 만들 때는, 최대한 단순화하여 장애를 격리하고 재사용성을 높이는 것이 중요합니다.
9 | 파이프라인을 복잡하게 만드는 또 다른 이유는 데이터 소스와 액세스 방법의 다양함입니다. 데이터가 여러 데이터 웨어하우스(RDB, NoSQL, NAS, 웹 API, 클라우드 스토리지, Hadoop 등)에 저장되면 각 데이터 웨어하우스에 대한 액세스, 인증 및 권한 부여를 정의하는 작업이 늘어나며 복잡해질 수 있습니다. 각 데이터 액세스 객체를 관리할 수 있는 추상화된 라이브러리를 사용하는 것을 권장하나, 여러 웨어하우스에 분산된 데이터는 데이터 엔지니어에게 시련과 고통을 줄 수 있습니다. 그러므로 적절하게 데이터 웨어하우스를 선택하고 정리하는 것이 중요합니다. 10 | 11 | ## Diagram 12 | ![diagram](diagram.png) 13 | 14 | 15 | ## Pros 16 | - 복잡한 파이프라인을 통해 다양한 작업들을 실행할 수 있습니다. 17 | 18 | ## Cons 19 | - 운영하기 어려울 수 있습니다. 20 | 21 | ## Work around 22 | - 파이프라인을 위한 의존성 관리를 합니다. 23 | - 항상 데이터가 정리되어야 합니다. 24 | 25 | ## Related design pattern 26 | - [Batch training pattern](./../../Batch-training-pattern/design_ko.md) 27 | - [Pipeline training pattern](./../../Pipeline-training-pattern/design_ko.md) -------------------------------------------------------------------------------- /Training-patterns/Anti-patterns/Too-many-pipes-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Training-patterns/Anti-patterns/Too-many-pipes-pattern/diagram.png -------------------------------------------------------------------------------- /Training-patterns/Anti-patterns/Training-code-in-serving-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Training code in serving pattern 2 | 3 | ## Case 4 | - Code only used for training, experiment and evaluation is included in serving. 5 | - Environment or configuration for training, experiment and evaluation is lest in serving. 6 | 7 | ## Situation 8 | Code and logic for machine learning development, which includes training, evaluation, experiment and anything before release, are probably different from those for the production serving. Difference in code may be difference in dependent library. For instance, you will write data splitting, batch training, parameter tuning and so on in your training code, though you will rarely use them for serving. Having different logic and code for training and serving is one of the difficulties of implementing machine learning into production system. It is recommended to not include useless code in your production in order to limit update, isolate fault and simplify code reading. It is better not to include training specific code into your serving environment.
9 | Resources used for training, such as CPU, GPU, RAM, network and storage, might be different in those for serving. In web services, network and storage for training may be limited to internal, and those for serving will be open to public. For deep learning, use of GPU for training and CPU for serving, or use of training GPU and inference GPU, is very much common practice. For these reasons, the environment configurations for training may be unnecessary, or misconfiguration, for serving environment. It is acceptable if the configuration is not-used, though if it is applicable, it may cause an incident.
10 | On the other hand, it is rather needed to have some common codes and configurations between training and serving to maintain same performance, latency and accuracy. It is important ot distinguish what to separate and what to standardize. 11 | 12 | - What to standardize between training and serving environment: 13 | - Versions of OS, language and library. 14 | - Code and logic used for inference, including preprocess, prediction and postprocess. 15 | - What to separate: 16 | - Training specific code and logic. 17 | - Dependencies to training specifig library and resource, including training GPU, large amount of CPU and RAM, internal network and internal DWH. 18 | 19 | ## Diagram 20 | ![diagram](diagram.png) 21 | 22 | 23 | ## Pros 24 | - For batch inference, you may be able to use the same environment for training and serving. 25 | 26 | ## Cons 27 | - You need to take time to separate training and serving specific code and configuration. 28 | 29 | ## Work around 30 | - Even if it is difficult to separate code and configuration for training and serving, recommended to at lease limit those related to cost, security and confidentiality, including network and data access. 31 | 32 | ## Related design pattern 33 | - [Serving patterns](./../../Serving-patterns/README.md) 34 | - [Training patterns](../README.md) -------------------------------------------------------------------------------- /Training-patterns/Anti-patterns/Training-code-in-serving-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Training code in serving pattern 2 | 3 | ## Case 4 | - 学習でしか使わないコードが推論器に残っている状態。 5 | - 実験や評価のためのロジックが推論器に残っている状態。 6 | - 学習や実験、評価のための環境設定が推論器に残っている状態。 7 | 8 | ## Situation 9 | 機械学習の開発(学習や検証、評価等、本番の推論器にリリースする前の段階)で書くロジックやコードが推論器で使うロジックやコードと異なることは多いと思います。コードが違えば依存するライブラリが違うこともあるでしょう。例えば学習であればデータ分割やバッチ学習、パラメータチューニング等のコードを実装しますが、推論でこれらのコードを使うことは稀です。学習と推論で違ったロジックやコードを使う点は機械学習をシステムに組み込む際の課題の一つです。本番システムの開発では、可能な限り不要なコードを含めない(リリースしない)ことで、更新範囲の決定や障害対応の切り分けが簡単になります。機械学習の推論器開発では、学習や検証、評価でしか使わないコードやライブラリは推論器に含めないほうが無難でしょう。
10 | 学習で使うリソース(CPU、GPU、RAM、ネットワーク、ストレージ等)が推論器で使うリソースと違うことがあります。Webサービスであれば、おそらくネットワークとストレージは学習環境(社内)と推論環境(Web向け)で全く異なる構成になるでしょう。また、ディープラーニングの場合、学習でGPUを活用しつつ、推論ではCPUを使う(または学習で学習用GPUを活用しつつ、推論では推論用GPUを使う)ということもあります。こうした理由により、学習環境で使うリソースの設定値は推論器では不要(または害悪)になることがあります。推論器で無効な設定値であれば良いですが、有効に使える設定値の場合、本番稼働する推論器で障害を起こす原因になることがあり、注意が必要です。
11 | 機械学習では学習と推論で異なる環境が使われることが一般的です。他方で、モデルを正常に稼働させるために(学習、評価時と同等のパフォーマンスを推論で発揮するために)、学習と推論でOSや言語、ライブラリ、前処理等を共通化する必要があります。学習と推論で共通化する部分と環境固有になる部分は区別することが重要です。 12 | 13 | - 学習と推論で共通にしたほうが良い部分: 14 | - OS、言語、ライブラリのバージョン。 15 | - 推論に関わるコードやロジック(前処理、推論実行、後処理)。 16 | - 個別に設定される部分: 17 | - 学習、検証、評価のコード。 18 | - 学習のためのライブラリやリソース(学習用GPU、大量のCPUやRAM、社内ネットワーク、社内向けDWH)。 19 | 20 | ## Diagram 21 | ![diagram](diagram.png) 22 | 23 | 24 | ## Pros 25 | - バッチ推論を行う場合は学習と推論で類似した環境が使えることがある。 26 | 27 | ## Cons 28 | - 学習と推論のコードやライブラリの整理が手間。 29 | 30 | ## Work around 31 | - 学習と推論でコードや設定を分割することが難しかったとしても、コストやセキュリティ、機密情報に関わる部分(ネットワークやデータへのアクセス等を含む)だけは必ず分離したほうが良い。 32 | 33 | ## Related design pattern 34 | - [Serving patterns](./../../Serving-patterns/README.md) 35 | - [Training patterns](../README.md) -------------------------------------------------------------------------------- /Training-patterns/Anti-patterns/Training-code-in-serving-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Training code in serving pattern 2 | 3 | ## Case 4 | - 학습, 실험, 평가에만 사용되야 하는 코드가 서빙 코드에 들어간 경우. 5 | - 학습, 실험, 평가를 위한 환경과 구성이 서빙에도 들어간 경우. 6 | 7 | ## Situation 8 | 학습, 실험, 평가 등 머신러닝 개발을 위한 코드와 로직은 대부분 실제 운영 서비스용과는 다릅니다. 예를 들어 코드 내에서 사용하는 라이브러리 의존성이 다를 수 있습니다. 또, 데이터 분산, 배치 학습, 파라미터 튜닝 등은 학습 단계에서 사용되지만 실제 서비스에서는 이러한 구현을 거의 하지 않습니다. 이러한 학습과 서빙의 다른 점이 머신러닝을 실제 운영 시스템에 적용하기 어려운 이유 중 하나입니다. 업데이트 제한, 장애 분리, 코드 가동성 등을 위하여 실제 시스템에는 불필요한 코드를 포함하지 않도록 해야 합니다. 특히, 학습 코드는 서빙 환경에 포함하지 않는 것이 좋습니다.
9 | CPU, GPU, RAM, 네트워크 및 스토리지와 같은 학습을 위한 리소스들은 서빙용과 따로 분리되어야 합니다. 웹 서비스의 경우, 학습을 위한 네트워크와 스토리지는 내부로 제한하고 서빙을 위한 것만 외부로 공게 해야 합니다. 또, 딥러닝의 경우, 학습용으로 GPU, 서빙용은 CPU를 사용하는 방법 혹은 학습용 GPU와 예측용 GPU를 따로 사용하는 방법이 일반적입니다. 이와 같은 이유들로, 학습 환경에서 사용하는 리소스 설정치들이 서비스 환경에서는 불필요 혹은 잘못된 설정들 일 수도 있습니다. 설정들을 포함하되 사용하지 않는 방법도 있으나 이럴 경우 장애로 이어질 수 있으므로 주의가 필요합니다.
10 | 하지만, 학습 단계의 퍼포먼스나, 지연시간, 정확성 등을 유지하기 위해서 코드나 설정을 동일하게 구성해야 할 때도 있습니다. 여기서 중요한 것은 무엇을 공통 표준화할 것이고 어떤 것은 분리하여 만들 것인가를 구분하는 것입니다. 11 | 12 | - 학습 및 서비스 환경의 표준화해야 하는 부분: 13 | - OS, 언어, 라이브러리 버전들 14 | - 전처리, 예측, 후처리 등에 사용되는 코드와 로직 15 | - 분리되어야 하는 부분: 16 | - 학습에 이용되는 코드와 로직 17 | - 학습을 위한 라이브러리나 리소스들(학습용 GPU, 대용량 CPU나 RAM, 내부 네트워크와 내부 데이터 웨어하우스)과의 의존성 18 | 19 | ## Diagram 20 | ![diagram](diagram.png) 21 | 22 | 23 | ## Pros 24 | - 배치 예측에서는 학습과 서빙을 동일한 환경에서 실행시킬 수도 있습니다. 25 | 26 | ## Cons 27 | - 학습용과 서빙용 코드와 설정들을 분리하는 수고가 필요합니다. 28 | 29 | ## Work around 30 | - 코드와 설정들을 분리하는 것이 당장은 어려울 수는 있으나, 장기적으로 비용과 보안, 기밀정보(네트워크와 데이터 액세스)보호 측면으로는 반드시 분리하는 것이 좋습니다. 31 | 32 | ## Related design pattern 33 | - [Serving patterns](./../../Serving-patterns/README_ko.md) 34 | - [Training patterns](../README_ko.md) 35 | -------------------------------------------------------------------------------- /Training-patterns/Anti-patterns/Training-code-in-serving-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Training-patterns/Anti-patterns/Training-code-in-serving-pattern/diagram.png -------------------------------------------------------------------------------- /Training-patterns/Batch-training-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Batch training pattern 2 | 3 | ## Usecase 4 | - To train on batch. 5 | - To schedule the batch. 6 | 7 | ## Architecture 8 | If you need to train your machine learning model regularly, the batch training pattern is applicable. In the pattern, you will define the training as a batch job and configure the trigger and schedule in a job management server. The server will execute the batch job. One of the easiest ways to define it is with Linux crontab, and it is also possible to make it with services in cloud. Or, it is possible to use a job management server.
9 | The pattern is one of the most common architecture to train a model offline. The workflow would be like: 10 | 1. Retrieve data from DWH (may need data cleansing) 11 | 2. Preprocess data 12 | 3. Train 13 | 4. Evaluate 14 | 5. Build model to prediction server 15 | 6. Store the model and server, and record the evaluation 16 | 17 | You may need to consider error handling of each step with the service level objective.
18 | If you need to keep updating the prediction model everyday or every batch, which means the service level is quite high, you would need retry policy for errors, or send an alert to an operating team. If you don't have to keep updated, you may just alert or record an error, and rekick later.
19 | It is recommended to make it possible to record failed job and rekick or troubleshoot from the log. Among the workflow above, there may have an irregular or unexpected data in the DWH, such as integer saved as char or invalid value range, that require some data anomaly filtering or data cleansing. It is difficult to rerun the job if there is anomaly data. You may need to filter the data beforehand or manually exclude it.
20 | For the steps 2. to 4., there may have possibility of the model evaluation may not be good enough for production use. In that case, you may need to reconsider preprocess or hyperparameter of the training and tune them to fit to the current dataset.
21 | For the 5. and 6., it may be system issue of building or recording error. You may need to review the system components, server, storage, database, network, middleware and so on, to find the root cause and mitigation.
22 | 23 | 24 | ## Diagram 25 | ![diagram](diagram.png) 26 | 27 | 28 | ## Pros 29 | - Retrain and update model regularly. 30 | 31 | ## Cons 32 | - Need to consider job error. 33 | - It is difficult to make a full-automatic workflow. 34 | 35 | ## Needs consideration 36 | - Job management method or software. 37 | - Error handling. 38 | -------------------------------------------------------------------------------- /Training-patterns/Batch-training-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Batch training pattern 2 | 3 | ## Usecase 4 | - 定期バッチでモデル学習を実行したいとき 5 | 6 | ## Architecture 7 | 機械学習のモデルを定期的に更新したい場合、バッチ学習パターンが有効です。学習をジョブとして定義し、ジョブ管理サーバにジョブの起動条件(日時、データ量、利用量等)を定義してジョブを実行することができます。ジョブ管理は簡単に構成するならLinuxのcronが使えますし、各種クラウドで提供されている定期実行サービスを活用することも可能です。SIerが提供するジョブ管理サーバも良いでしょう。
8 | バッチ学習パターンはオフラインでモデル学習する最も典型的なアーキテクチャーになります。バッチのジョブフローには以下が含まれます。 9 | 1. DWHからデータ収集(データの異常診断含む) 10 | 2. データの前処理 11 | 3. 学習 12 | 4. 評価 13 | 5. モデルおよび推論器のビルド 14 | 6. モデル、推論器、評価の記録 15 | 16 | 各フローでエラーが発生した際の対処はバッチと推論器のサービスレベル次第で検討します。
17 | 推論モデルを常に最新に保つ必要がある場合(サービスレベルが高い)、エラー時にはリトライするか、運用者に通報する必要があります。常に最新である必要がなければ、エラー通報だけしておいて、翌日等に手動で実行するものでも良いでしょう。
18 | エラーが発生した場合は、エラー箇所を記録し、エラーログから復旧手段やトラブルシューティングを実施できるようにしておく必要があります。上記ジョブフローのうち、1.では外部の入力データが不良である可能性があるため、データの異常診断や異常値検出等を行うことが妥当です(Int値にChar値が入っている、0~1の範囲に収まる筈の値に10が含まれている等々)。異常データが含まれていたためにジョブが停止した場合、自動リトライで対応することは不可能なため、事前に異常値を除外する実装にするか、マニュアルで除外する必要があります。
19 | 他方で2.~4.においては、モデルの性能(評価値)が必要なサービスレベルを満たさない可能性も考えられます。この場合、前処理方法やハイパーパラメータが現状のデータに適合していない可能性が考えられるため、データ分析とモデルのチューニングが必要になります。
20 | 5.と6.はビルドエラーや記録エラー等、システム障害に起因する場合が考えられます。ビルドや記録に使用しているシステム(サーバ、ストレージ、データベース、ネットワーク等)の障害レポートを確認する必要があります。
21 | 22 | 23 | ## Diagram 24 | ![diagram](diagram.png) 25 | 26 | 27 | ## Pros 28 | - 定期的にモデルを学習し更新することが可能。 29 | 30 | ## Cons 31 | - ジョブのエラー時対応を検討しておく必要があり、完全自動運用は困難な場合が多い。 32 | 33 | ## Needs consideration 34 | - ジョブ管理サーバの選定。 35 | - エラー時の対応方法。 36 | -------------------------------------------------------------------------------- /Training-patterns/Batch-training-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Batch training pattern 2 | 3 | ## Usecase 4 | - 배치로 학습시킬 경우. 5 | - 배치 작업을 주기적으로 실행 시킬 경우. 6 | 7 | ## Architecture 8 | 머신러닝 모델을 정기적으로 학습시켜야 할 경우, Batch training pattern을 고려해볼 수 있습니다. 이 패턴에서는 배치 작업으로 학습을 정의하고 작업 관리 서버에서 정기적으로 실행될 수 있도록 설정을 해야 합니다. 배치 작업을 주기적으로 실행시키기 위해 Linux의 crontab을 사용할 수 있으며, 클라우드 서비스를 이용하거나 별도의 작업 관리 서버를 사용할 수도 있습니다.
9 | 이 패턴은 오프라인에서 모델을 학습시키는 가장 일반적인 아키텍처 중 하나로, 워크플로우는 다음과 같습니다: 10 | 11 | 1. 데이터 웨어하우스에서 데이터 수집(데이터 정제 작업이 필요할 수 있음.) 12 | 2. 데이터 전처리 13 | 3. 학습 14 | 4. 평가 15 | 5. 예측 서버에 모델 구축 16 | 6. 모델과 서버, 평가 기록 17 | 18 | 서비스의 목표 수준에 따라 각 단계에서 오류 처리를 어떻게 할지 고려해보아야 합니다.
19 | 예측 모델을 매일 또는 매번 업데이트를 하는 경우(서비스의 요구 레벨이 높은 경우), 에러에 대하여 재시도 정책을 갖거나, 운영팀에 알람을 보내는 등의 정책을 정할 수 있습니다. 만약 업데이트가 꼭 지속될 필요가 없다면, 에러를 저장하거나 알림만 보내고 나중에 다시 처리할 수도 있습니다.
20 | 실패한 작업에 대해서는 에러를 저장하고 로그를 통해 재처리 혹은 트러블슈팅을 하는 것이 좋습니다. 위의 워크플로우 1단계에서 데이터 수집 중에 잘못되거나 예상치 못한 데이터(예를 들어 Int 값에 Char 값, 잘못된 범위 등)가 들어올 수 있으므로 데이터 필터링 혹은 데이터 정제 작업이 필요합니다. 정상적이지 않은 데이터가 있다면 작업을 재실행하기 어렵습니다. 그러므로 데이터를 사전에 필터링하거나 수동으로 제외하는 작업을 해야 할 수도 있습니다.
21 | 2단계부터 4단계에서 모델의 성능이 실제 서비스용으로는 부족할 수도 있습니다. 이러한 경우, 학습의 전처리 또는 하이퍼파라미터에 대해 재고하여 현재 데이터 세트에 맞게 튜닝할 수 있습니다.
22 | 5와 6단계에서는 빌드 에러나 기록 에러 등 시스템 장애들을 고려해보아야 합니다. 이를 위해 시스템 구성 요소, 서버, 스토리지, 데이터베이스, 네트워크, 미들웨어 등을 검토하고 시스템 이슈의 근본적인 원인과 해결 방법 등을 찾을 수 있습니다.
23 | 24 | 25 | ## Diagram 26 | ![diagram](diagram.png) 27 | 28 | 29 | ## Pros 30 | - 정기적인 재학습과 모델 업데이트. 31 | 32 | ## Cons 33 | - 작업 에러 사항을 고려해야 합니다. 34 | - 완전한 자동 워크플로우를 만들기 어렵습니다. 35 | 36 | ## Needs consideration. 37 | - 작업 관리 방법과 소프트웨어. 38 | - 에러 처리 방법. 39 | -------------------------------------------------------------------------------- /Training-patterns/Batch-training-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Training-patterns/Batch-training-pattern/diagram.png -------------------------------------------------------------------------------- /Training-patterns/Parameter-and-architecture-search-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Parameter and architecture search pattern 2 | 3 | ## Usecase 4 | - To automatically search for parameter and architecture of a model. 5 | - When manual tuning is difficult. 6 | 7 | ## Architecture 8 | The parameter and architecture search pattern aims to design workflow to automate hyperparameter and architecture search. It is possible to search for the hyperparameter and architecture based on dataset and evaluation function to reduce manual task of model development. Hyperparameter is a parameter whose value is set before the learning process begins to control training criteria, such as depth of decisiontree, activation function in multilayer perceptron, etc. Common methods for hyperparameter search are grid search, random search, evolutionary algorithm, and bayesian optimization. Architecture is a overall structure of the model, such as inception and resnet in neural network. Common methods include neural architecture search in reinforcement learning and usage of gradient descent. In any methods, their aim is to search for an optimized machine learning model.
9 | The pipeline runs in a cycle of search, train and evaluate. You may use the pattern to be implemented in your model training process. The aim is to add the search mechanism, and make it possible to simultaneously optimize and train a model. It is necessary to configure parameters for the search in addition to training pipeline. Once you retrieved your training dataset, the training job will be executed with the parameters to search for a model and evaluate. Some search mechanism chooses next hyperparameter or architecture to train. The cycle completes depending on the number of loops, number of candidate parameters, time, or evaluation. Last but not least, be sure to record the model into your model repository.
10 | If there is a best practice for your purpose, or if it is well enough with transfer learning or retraining, the pattern is not the right choise. It is useful when you need to search or optimize for your specific problem. 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - Automatically tune a machine learning model. 18 | - Possible to discover a model that could not be manually. 19 | 20 | ## Cons 21 | - Needs parameter to search. 22 | - Computational cost. 23 | 24 | ## Needs consideration 25 | - Parameter search or architecture search. 26 | - Algorithms for parameter search and architecture search. 27 | - Parameters for the algorithm. 28 | - Cost. -------------------------------------------------------------------------------- /Training-patterns/Parameter-and-architecture-search-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Parameter and architecture search pattern 2 | 3 | ## Usecase 4 | - 機械学習モデルの学習前にモデルの最適なハイパーパラメータやアーキテクチャを自動探索したいとき 5 | - 手動でモデル設計やハイパーパラメータ調整をすることが難しいとき 6 | 7 | ## Architecture 8 | パラメータ&アーキテクチャ探索パターンは機械学習モデルのハイパーパラメータやアーキテクチャを自動探索するワークフローです。データセットと評価関数に応じたハイパーパラメータやアーキテクチャを自動的に探索することにより、手動でのモデル開発を行う工数を省力化することが可能になります。ハイパーパラメータは学習プロセスを管理する値(分類木の深さやニューラルネットワークの活性化関数等)、アーキテクチャはモデルの全体像(ニューラルネットワークの構造等)を言います。ハイパーパラメータ探索で有名な手法としては、グリッド・サーチ、ランダム・サーチ、遺伝アルゴリズム、ベイズ最適化があります。アーキテクチャ探索では、主にニューラルネットワークの探索手法として、強化学習によるニューラル・アーキテクチャ・サーチや微分によるニューラル・アーキテクチャ・サーチがあります。いずれにおいても、最適な機械学習モデルを自動的に探索する手法になります。
9 | パラメータ&アーキテクチャ探索パターンは、ハイパーパラメータ探索やアーキテクチャ探索を学習プロセスに組み込むことを目的としています。ワークフローに組み込み、バッチ・ジョブ等で起動できるようにすることで、機械学習モデルの最適化と学習を統合する狙いです。この場合、ハイパーパラメータ探索アルゴリズムやアーキテクチャ探索アルゴリズムおよび、それらの設定値を用意する必要があります。学習用データの取得後、パラメータ&アーキテクチャ探索ジョブにデータを入力します。パラメータ&アーキテクチャ探索ジョブでは、探索設定値に応じてモデル探索を行い、学習、評価を実行します。評価結果に応じて次のパラメータやアーキテクチャを決定し、再度学習と評価を実行します。探索→学習→評価のループは、ループ回数や探索対象候補数、時間、評価目標値等で完了します。生成されたモデルは、最後に最適なものをモデル管理システムに記録します。
10 | 問題空間に対するベストプラクティスがすでに確立している、または転移学習や再学習で良いモデルを作ることができる場合、本パターンは不向きです。新たなモデル探索や最適化が必要な際に有効なパターンになります。 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - 機械学習モデルを自動的にチューニングすることで、省力化を図ることが可能。 18 | - 手動では発見できないアーキテクチャを生成する可能性もある。 19 | 20 | ## Cons 21 | - 探索の設定値を用意する必要がある。 22 | - 探索中の計算リソースにコストが発生する。 23 | 24 | ## Needs consideration 25 | - パラメータ探索か、アーキテクチャ探索か 26 | - パラメータ探索アルゴリズムまたはアーキテクチャ探索アルゴリズムの選定 27 | - 各探索アルゴリズムの設定値 28 | - コスト対効果 -------------------------------------------------------------------------------- /Training-patterns/Parameter-and-architecture-search-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Parameter and architecture search pattern 2 | 3 | ## Usecase 4 | - 모델의 파라미터와 아키텍처를 자동으로 탐색하고 싶을 경우. 5 | - 수동으로 모델을 조정하기 어려울 경우. 6 | 7 | ## Architecture 8 | Parameter and architecture search pattern은 하이퍼 파라미터와 아키텍처 탐색을 자동으로 하는 것을 목표로 합니다. 데이터 세트와 평가를 바탕으로 하이퍼 파라미터와 아키텍처를 자동으로 탐색할 수 있게 함으로써 모델 개발에서 수동 업무를 줄일 수 있습니다. 하이퍼파라미터는 학습 과정이 시작되기 전에 설정되는 값으로, 예를 들어 의사결정 나무(Decisiontree)의 깊이, 멀티레이어 퍼셉트론(Multilayer perceptron)의 활성화 기능 등이 있습니다. 하이퍼 파라미터 탐색 방법으로는 그리드 서치, 랜덤 서치, 진화 알고리즘(Evolutionary algorithm), 그리고 베이지안 최적화(Bayesian optimization) 등이 있습니다. 아키텍처는 인셉션과 신경망의 레스넷(Resnet)과 같은 모델의 전체적인 구조를 말합니다. 아키텍처 탐색에서는 강화 학습의 Neural architecture search와 Gradient descent 이용 방법이 있습니다. 위 방법들은 최적화된 머신러닝 모델을 찾기 위한 방법들입니다.
9 | 이 파이프라인은 탐색->학습->평가의 사이클로 실행됩니다. 모델 학습 구현 과정에서 이 패턴을 사용할 수 있습니다. 이 패턴에서는 탐색 메커니즘을 추가하고 동시에 모델을 최적화하며 학습시키는 것을 목표로 하고 있습니다. 이 경우, 학습용 파이프라인 외에 탐색에 대한 파라미터 구성을 해야 합니다. 먼저, 학습용 데이터셋을 검색한 후, 모델을 검색하고 평가하기 위한 파라미터를 사용하여 학습 작업이 실행됩니다. 일부 검색 메커니즘은 학습할 다음 하이퍼파라미터 또는 아키텍처를 선택합니다. 탐색→학습→평가의 사이클은 반복 횟수, 후보 파라미터의 개수, 시간 그리고 평가 목표치 등에 따라 사이클이 완료됩니다. 이를 통해 생성된 모델은 마지막에 최적인 모델로 모델 관리시스템에 기록합니다.
10 | 이미 목적에 맞는 베스트 프렉티스가 확립되어 있거나, 전이 학습이나 재학습으로 좋은 모델을 만들 수 있다면 이 패턴은 적합하지 않습니다. 특정 문제에 대한 새로운 모델 탐색 혹은 최적화가 필요할 때 유용한 패턴입니다. 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - 머신러닝 모델 자동 튜닝. 18 | - 수동으로 확인 할 수 없는 모델 탐색. 19 | 20 | ## Cons 21 | - 탐색할 파라미터 값. 22 | - 계산을 위한 비용 발생. 23 | 24 | ## Needs consideration 25 | - 파라미터 탐색 혹은 아키텍쳐 탐색. 26 | - 파라미터 탐색과 아키텍쳐 탐색을 위한 알고리즘. 27 | - 알고리즘에 대한 파라미터 값. 28 | - 비용. 29 | -------------------------------------------------------------------------------- /Training-patterns/Parameter-and-architecture-search-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Training-patterns/Parameter-and-architecture-search-pattern/diagram.png -------------------------------------------------------------------------------- /Training-patterns/Pipeline-training-pattern/design_en.md: -------------------------------------------------------------------------------- 1 | # Pipeline training pattern 2 | 3 | ## Usecase 4 | - When you need to separate each step of the training pipeline to make it possible to select library on its own and reusable. 5 | - In order to make retry easier with recording status and process in each job. 6 | - To control each job separately. 7 | 8 | ## Architecture 9 | The pipeline training pattern is a advancement of the batch training pattern. Each job is defined as separate resources, server, container, or worker, to make it possible to deploy the job resource independently to run and retry the job flexibly. Since the job will be deployed as a separate resource, it will be executed after the dependent job. The result of the former job will be succeeded to the latter as its input data. For sake of fault tolerance, the processed data can be stored in DWH. You don't have to run the job right after the former job completion. It is possible to run the time-consuming job frequently, and other jobs not so often.
10 | Note that the pattern may make the job workflow and resource management complex. While it increases independency of the job, you need to select resource and define jobs. 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - Possible to define job and select library flexibly. 18 | - Fault isolation. 19 | - Manage job based on workflow or data. 20 | 21 | ## Cons 22 | - You need to manage multiple jobs in multiple structure. 23 | - System and workflow may be complex. 24 | 25 | ## Needs consideration 26 | - Resource management, library management and version management. 27 | -------------------------------------------------------------------------------- /Training-patterns/Pipeline-training-pattern/design_ja.md: -------------------------------------------------------------------------------- 1 | # Pipeline training pattern 2 | 3 | ## Usecase 4 | - 学習パイプラインのリソースを分割し、各ジョブでライブラリ選定や流用を可能にしたいとき 5 | - 各ジョブ毎にデータの状態や進行を記録し、リトライを簡単にしたいとき 6 | - 各ジョブの実行を個別にコントロールしたいとき 7 | 8 | ## Architecture 9 | パイプライン学習パターンはバッチ学習パターンの応用版です。各ジョブを個別のリソース(サーバ、コンテナ、ワーカー等)に分割することで、ジョブ・リソースを個別に構築することを可能にし、柔軟なりトライやジョブ実行を実現します。パイプライン学習パターンではジョブが個別リソースに分割されるため、依存関係にあるジョブの実行後に次のジョブ実行を可能にします。前ジョブの実行結果は後続ジョブに提供され、後続ジョブの入力データとなります。耐障害性のため、処理済みデータをDWHに格納することも可能です。前ジョブ完了直後に必ず後ジョブを実行する必要はありません。時間のかかる前ジョブの実行頻度を上げておいて、後段のジョブは低頻度で実行する、という構成も可能です。
10 | パイプライン学習パターンの難点は個別ジョブのリソース管理やコード管理等が複雑になることです。各ジョブの独立性を高める利点がある一方で、ジョブの実行条件やリソース選択等を個別に検討する必要があります。 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - ジョブのリソースやライブラリ選定等を柔軟に実施可能。 18 | - ジョブのエラー箇所を分離しやすい。 19 | - ワークロードやデータに応じた柔軟なジョブ管理が可能。 20 | 21 | ## Cons 22 | - 各ジョブリソースの管理が必要になる。 23 | - システムが複雑になる傾向にある。 24 | 25 | ## Needs consideration 26 | - ジョブのリソース管理、ライブラリ管理、バージョン管理方法。 27 | -------------------------------------------------------------------------------- /Training-patterns/Pipeline-training-pattern/design_ko.md: -------------------------------------------------------------------------------- 1 | # Pipeline training pattern 2 | 3 | ## Usecase 4 | - 학습용 파이프라인 단계를 분리하여 각각의 라이브러리를 선택하고 재사용을 할 수 있도록 만드는 경우. 5 | - 각각의 작업마다 데이터 상태와 진행을 기록하고 재시도를 용이하게 만드는 경우. 6 | - 각 작업들을 별도로 컨트롤하고자 하는 경우. 7 | 8 | ## Architecture 9 | Pipeline training pattern은 Batch training pattern의 응용 패턴입니다. 각 작업을 개별 리소스(서버, 컨테이너, 워커 등)로 분할함으로써 작업과 리소스를 개별적으로 구축할 수 있게 하여 작업 실행과 재시도를 유연하게 실행시킬 수 있습니다. 이 패턴에서 모든 작업들은 개별 리소스로 배치되기 때문에, 의존 관계가 있는 작업 후에 실행됩니다. 이전 작업의 실행 결과는 후속 작업에 제공되며 후속 작업의 입력 데이터가 됩니다. fault tolerance(결함 감내. 시스템을 구성하는 일부에서 결함 또는 고장이 발생하여도 정상적 혹은 부분적으로 기능을 수행)를 위하여 처리 완료 데이터를 데이터 웨어하우스에 저장할 수도 있습니다. 이전 작업을 완료하자마자 바로 다음 작업을 실행할 필요는 없습니다. 시간이 많이 걸리는 작업은 자주 실행하고 다른 작업들은 더 적게 실행할 수 도 있습니다.
10 | 이 패턴으로 인해 작업 워크플로우와 리소스 관리가 복잡해 줄 수 있습니다. 각 작업의 독립성을 높이는 장점이 있지만, 작업의 실행 조건이나 리소스 선택 등을 개별적으로 고려해야 합니다. 11 | 12 | ## Diagram 13 | ![diagram](diagram.png) 14 | 15 | 16 | ## Pros 17 | - 작업의 리소스나 라이브러리를 유연하게 선택할 수 있습니다. 18 | - 장애 분리. 19 | - 워크플로우 또는 데이터 기반의 작업 관리. 20 | 21 | ## Cons 22 | - 다중 구조로 여러 작업들을 관리해야 합니다. 23 | - 시스템 및 워크플로우가 복잡해 질 수 있습니다. 24 | 25 | ## Needs consideration 26 | - 리소스, 라이브러리, 버전 관리 방법. 27 | -------------------------------------------------------------------------------- /Training-patterns/Pipeline-training-pattern/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mercari/ml-system-design-pattern/ec00617270d54666ab4070951f6639c77220cc42/Training-patterns/Pipeline-training-pattern/diagram.png -------------------------------------------------------------------------------- /Training-patterns/README.md: -------------------------------------------------------------------------------- 1 | # Training patterns 2 | - [Batch training pattern](./Batch-training-pattern/design_en.md) 3 | 4 | 5 | - [Pipeline training pattern](./Pipeline-training-pattern/design_en.md) 6 | 7 | 8 | - [Parameter and architecture search pattern](./Parameter-and-architecture-search-pattern/design_en.md) 9 | 10 | 11 | - [Antipatterns](./Anti-patterns/README.md) 12 | 13 | - [Only-me pattern](./Anti-patterns/Only-me-pattern/design_en.md) 14 | 15 | - [Training code in serving pattern](./Anti-patterns/Training-code-in-serving-pattern/design_en.md) 16 | 17 | - [Too many pipes pattern](./Anti-patterns/Too-many-pipes-pattern/design_en.md) -------------------------------------------------------------------------------- /Training-patterns/README_ja.md: -------------------------------------------------------------------------------- 1 | # Training patterns 2 | - [Batch training pattern](./Batch-training-pattern/design_ja.md) 3 | 4 | 5 | - [Pipeline training pattern](./Pipeline-training-pattern/design_ja.md) 6 | 7 | 8 | - [Parameter and architecture search pattern](./Parameter-and-architecture-search-pattern/design_ja.md) 9 | 10 | 11 | - [Antipatterns](./Anti-patterns/README_ja.md) 12 | 13 | - [Only-me pattern](./Anti-patterns/Only-me-pattern/design_ja.md) 14 | 15 | - [Training code in serving pattern](./Anti-patterns/Training-code-in-serving-pattern/design_ja.md) 16 | 17 | - [Too many pipes pattern](./Anti-patterns/Too-many-pipes-pattern/design_ja.md) -------------------------------------------------------------------------------- /Training-patterns/README_ko.md: -------------------------------------------------------------------------------- 1 | # Training patterns 2 | - [Batch training pattern](./Batch-training-pattern/design_ko.md) 3 | 4 | 5 | - [Pipeline training pattern](./Pipeline-training-pattern/design_ko.md) 6 | 7 | 8 | - [Parameter and architecture search pattern](./Parameter-and-architecture-search-pattern/design_ko.md) 9 | 10 | 11 | - [Antipatterns](./Anti-patterns/README_ko.md) 12 | 13 | - [Only-me pattern](./Anti-patterns/Only-me-pattern/design_ko.md) 14 | 15 | - [Training code in serving pattern](./Anti-patterns/Training-code-in-serving-pattern/design_ko.md) 16 | 17 | - [Too many pipes pattern](./Anti-patterns/Too-many-pipes-pattern/design_ko.md) -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /template_antipattern.md: -------------------------------------------------------------------------------- 1 | # antipattern name 2 | 3 | ## Case 4 | - 5 | 6 | ## Situation 7 | 8 | 9 | ## Diagram 10 | ![diagram](diagram.png) 11 | 12 | 13 | ## Pros 14 | - 15 | 16 | ## Cons 17 | - 18 | 19 | ## Work around 20 | - 21 | 22 | ## Related design pattern 23 | - -------------------------------------------------------------------------------- /template_design.md: -------------------------------------------------------------------------------- 1 | # pattern name 2 | 3 | ## Usecase 4 | - 5 | 6 | ## Architecture 7 | 8 | 9 | ## Diagram 10 | ![diagram](diagram.png) 11 | 12 | 13 | ## Pros 14 | - 15 | 16 | ## Cons 17 | - 18 | 19 | ## Needs consideration 20 | - 21 | --------------------------------------------------------------------------------