{ "cells": [ { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "# Part 1 - WML Federated Learning with MNIST for Admin " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "IBM Federated Learningを利用すれば、実際にデータを共有することなく、複数のソースからのデータを組み合わせて、集合データからモデルをトレーニングすることができます。 \n", "これにより、企業はセキュリティのためにリソースを委譲することなく、他社とデータのトレーニングを行うことができます。 \n", "もう一つの利点は、リモートデータを一箇所に集中管理する必要がないため、潜在的に大規模なデータセットを移動させる必要がないことです。 \n", "このノートブックでは、Pythonクライアントを使用して連携学習を開始する方法をデモします。 \n", "Federated Learningのセットアップ、用語、UIからのFederated Learningの実行などの詳細については、[Federated Learningのドキュメント](https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fed-lea.html?audience=wdp)を参照してください。\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 学習目標\n", "\n", "Part11 - WML Federated Learning with MNIST for Adminノートブックを終了すると、以下のようなことができるようになります。\n", "\n", "- 未学習モデルをロードする\n", "- リモートトレーニングシステムの作成\n", "- トレーニング・ジョブの開始\n", "\n", "このノートを完成させたら、Part 2 - WML Federated Learning with MNIST for Partyを開いてください。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
このノートはFederated Learning実験の管理者が実行することを想定しています。
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 目次\n", "\n", "- [1.前提条件](#prequisites)\n", " - [1.1 変数の定義](#var)\n", " - [1.2 ライブラリのインポート](#libraries)\n", " - [1.3 クラウド認証トークンの取得](#cloud-auth)\n", "- [2.モデルの読み込み](#load)\n", " - [2.1 未学習モデル資産の作成](#model)\n", " - [2.2 初期モデルのアップロード](#init)\n", "- [3.リモートトレーニングシステムの作成](#rts)\n", " - [3.1 リモートトレーニングシステム資産の作成](#create-rts)\n", "- [4.FLトレーニングジョブを作成](#fl-job)\n", " - [4.1 トレーニングジョブのステータス取得](#status)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Cloud Object Storage バケット。IBM Cloud Services](https://cloud.ibm.com/resources)のCloud Object Storageインスタンスから作成できます。\n", "- HMACを有効にしたCloud Object Storageサービスクレデンシャル。作成するには、**Cloud Object Storage < Service Credentials** に移動し、**New credentials** をクリックします。ライターアクセスを与えて、**Advanced options**をクリックし、*Include HMAC Credential*をオンにします。\n", "- IAM API キー。新しいキーを作成するには、[IBM Cloud ホームページ](https://cloud.ibm.com) にアクセスします。アカウントで、**Manage < IAM < API Keys**に移動します。**Create an IBM Cloud API Key**をクリックします。\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 1.1 変数の定義" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 共通設定" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "API_VERSION = \"2019-10-25\"\n", "IAM_TOKEN_URL = \"https://iam.cloud.ibm.com/oidc/token\"\n", "IAM_APIKEY = \"xxxx\"\n", "\n", "# Manage < IAM < Usersから取得し、URLを確認します。ユーザーIDはIBMid-の形式になっているはずです。\n", "CLOUD_USERID = \"xxxx\"\n", "\n", "# Studioプロジェクトに入ってURLを確認することで取得できます。\n", "PROJECT_ID =\"xxxx\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### WML設定" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# WMLのロケーションにより変更します\n", "WML_SERVICES_HOST = \"us-south.ml.cloud.ibm.com\"\n", "WML_SERVICES_URL = \"https://\" + WML_SERVICES_HOST" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### COS設定\n", "次のリンクからエンドポイントのURLを探します: \n", "https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-endpoints" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# COS設定\n", "COS_ENDPOINT_URL = \"https://s3.us-south.cloud-object-storage.appdomain.cloud\" \n", "\n", "# HMACサービスの資格情報からアクセスキーIDとSECRET_ACCESS_KEYをCOS用に取得します\n", "COS_ACCESS_KEY_ID = \"xxxx\"\n", "COS_SECRET_ACCESS_KEY = \"xxxx\"\n", "\n", "# COS bucket名\n", "COS_BUCKET = \"xxxx\" \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 1.2 ライブラリのインポート" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import urllib3\n", "import requests\n", "import json\n", "from string import Template\n", "\n", "urllib3.disable_warnings()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 1.3 クラウド認証トークンの取得" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "payload = \"grant_type=urn:ibm:params:oauth:grant-type:apikey&apikey=\" + IAM_APIKEY\n", "token_resp = requests.post(IAM_TOKEN_URL ,\n", " headers={\"Content-Type\": \"application/x-www-form-urlencoded\"}, \n", " data = payload,\n", " verify=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 結果確認\n", "print(token_resp)\n", "\n", "token = \"Bearer \" + json.loads(token_resp.content.decode(\"utf-8\"))[\"access_token\"]\n", "print(\"WS token: %s \" % token)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 2. モデルの読み込み" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Federated Learningで作業するためには、未訓練のモデルアセットが必要です。 \n", "このチュートリアルでは、未学習の Tensorflow 2 Keras モデルを提供します。 \n", "Federated Learning は Scikit-learn と Tensorflow 2 をサポートしています。 \n", "さらに、IBM のドキュメントには、Federated Learning のための非訓練モデルの設定方法についての詳細が記載されています。参照してください。\n", "\n", "- [Scikit-learnモデルの設定](https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fl-imp-det.html?audience=wdp&context=cpdaas#sklearn-config)\n", "- [Tensorflow 2のモデル構成](https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fl-imp-det.html?audience=wdp&context=cpdaas#tf-config)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 2.1 未学習モデル資産の作成\n", "\n", "プロジェクト内に未訓練のモデルアセットを作成します。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "base_model_save_payload = Template(\"\"\"\n", "{\n", " \"name\": \"Untrained MNIST Model\",\n", " \"type\": \"tensorflow_2.1 \",\n", " \"software_spec\": {\n", " \"name\": \"default_py3.7\"\n", " },\n", " \"custom\": {\n", " \"untrained\" : true\n", " },\n", " \"project_id\": \"$projectId\"\n", "}\n", "\"\"\").substitute(projectId = PROJECT_ID)\n", "\n", "print (\"Model base save payload: %s\" % base_model_save_payload)\n", "\n", "base_model_save_resp = requests.post(WML_SERVICES_URL + \"/ml/v4/models\",\n", " headers={\"Content-Type\": \"application/json\",\n", " \"Authorization\": token},\n", " params={\"version\": API_VERSION},\n", " data=base_model_save_payload,\n", " verify=False)\n", "\n", "print(\"Base model save response \" + base_model_save_resp.content.decode(\"utf-8\"))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "base_model_id = json.loads(base_model_save_resp.content.decode(\"utf-8\"))[\"metadata\"][\"id\"]\n", "print(\"Saved model id: %s\" % base_model_id)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 2.2 初期モデルのアップロード" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "初期モデルをプロジェクトにアップロードする必要があります。 \n", "このチュートリアルでは、訓練されていないモデルの例が提供されており、[GitHub](https://github.com/IBMDataScience/sample-notebooks/blob/master/Files/tf_mnist_model.zip).からダウンロードすることができます。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "base_model_content_resp = requests.get(\"https://github.com/IBMDataScience/sample-notebooks/raw/master/Files/tf_mnist_model.zip\",\n", " headers={\"Content-Type\": \"application/octet-stream\"})\n", "\n", "base_model_content_uri = \"/ml/v4/models/\"+ base_model_id + \"/content\"\n", "print(\"Host URL = \" + WML_SERVICES_URL + base_model_content_uri)\n", "\n", "base_model_put_resp = requests.put(WML_SERVICES_URL + base_model_content_uri,\n", " headers={\"Content-Type\": \"application/json\",\n", " \"Authorization\": token},\n", " params={\"version\": API_VERSION,\n", " \"project_id\": PROJECT_ID,\n", " \"content_format\": \"native\"},\n", " data=base_model_content_resp.content,\n", " verify=False)\n", "\n", "print(\"Response status for upload base model \" + base_model_id + \" : \"+ str(base_model_put_resp.status_code))\n", "print(\"Create library content: %s\" % base_model_put_resp.content.decode(\"utf-8\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 3. リモートトレーニングシステムの作成" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "今、あなたはリモートトレーニングシステム(RTS)を作成することを学びます。RTSは、トレーニングを実行するためのアグリゲータへの複数の当事者の呼び出しの受信を処理します。\n", "- allowed_identities` は、Federated Learning実験への接続を許可するユーザです。 このチュートリアルでは、あなたのユーザIDのみが接続を許可されていますが、必要に応じてテンプレートを更新してユーザを追加することができます。\n", "- remote_admin`の管理者です。管理者のテンプレートはユーザと同じです。このチュートリアルでは、テンプレートAdminを作成します。これもユーザIDと同じですが、一般的にアプリケーションでは管理者はユーザの一人である必要はありません。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "wml_remote_training_system_asset_one_def = Template(\"\"\"\n", "{\n", " \"name\": \"Remote Party 1\",\n", " \"project_id\": \"$projectId\",\n", " \"description\": \"Sample Remote Training System\",\n", " \"tags\": [ \"Federated Learning\" ],\n", " \"organization\": {\n", " \"name\": \"IBM\",\n", " \"region\": \"US\"\n", " },\n", " \"allowed_identities\": [\n", " {\n", " \"id\": \"$userID\",\n", " \"type\": \"user\"\n", " }\n", " ],\n", " \"remote_admin\": {\n", " \"id\": \"$userID\",\n", " \"type\": \"user\"\n", " }\n", "}\n", "\"\"\").substitute(userID = CLOUD_USERID,\n", " projectId = PROJECT_ID)\n", "\n", "\n", "wml_remote_training_system_one_resp = requests.post(WML_SERVICES_URL + \"/ml/v4/remote_training_systems\", \n", " headers={\"Content-Type\": \"application/json\",\n", " \"Authorization\": token}, \n", " params={\"version\": API_VERSION,\n", " \"project_id\": PROJECT_ID}, \n", " data=wml_remote_training_system_asset_one_def, \n", " verify=False)\n", "\n", "print(wml_remote_training_system_one_resp)\n", "status_json = json.loads(wml_remote_training_system_one_resp.content.decode(\"utf-8\"))\n", "print(\"Create wml_remote_training_system_one asset response: %s\" % json.dumps(status_json, indent=4))\n", "wml_remote_training_system_one_asset_uid = status_json[\"metadata\"][\"id\"]\n", "print(\"WML wml_remote_training_system_one asset uid: %s\" % wml_remote_training_system_one_asset_uid)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 4. FLトレーニングジョブを作成\n", "\n", "このセクションでは、Federated Learningの実験を開始します。\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "training_payload = Template(\"\"\" \n", "{\n", " \"name\": \"FL Aggregator\",\n", " \"tags\": [\n", " {\n", " \"value\": \"tags_jobs_fl\",\n", " \"description\": \"Sample FL Aggregator\"\n", " }\n", " ],\n", " \"federated_learning\": {\n", " \"model\": {\n", " \"spec\": {\n", " \"id\": \"$modelID\"\n", " },\n", " \"type\": \"tensorflow\"\n", " },\n", " \"fusion_type\": \"iter_avg\",\n", " \"rounds\": 5,\n", " \"remote_training\" : {\n", " \"quorum\": 1.0,\n", " \"remote_training_systems\": [ { \"id\" : \"$rts_one\", \"required\" : true } ]\n", " },\n", " \"hardware_spec\": {\n", " \"name\": \"XS\"\n", " }\n", " },\n", " \"training_data_references\": [],\n", " \"results_reference\": {\n", " \"type\": \"s3\",\n", " \"name\": \"outputData\",\n", " \"connection\": {\n", " \"endpoint_url\": \"$endpoint\",\n", " \"access_key_id\": \"$accessId\",\n", " \"secret_access_key\": \"$secretKey\"\n", " },\n", " \"location\": {\n", " \"bucket\": \"$bucket\",\n", " \"path\": \".\"\n", " }\n", " },\n", " \"project_id\": \"$projectId\" \n", "}\n", "\"\"\").substitute(modelID = base_model_id,\n", " projectId = PROJECT_ID,\n", " rts_one = wml_remote_training_system_one_asset_uid,\n", " endpoint = COS_ENDPOINT_URL,\n", " accessId = COS_ACCESS_KEY_ID,\n", " secretKey = COS_SECRET_ACCESS_KEY,\n", " bucket = COS_BUCKET)\n", "\n", "print(\"Training payload: %s\" % training_payload)\n", "\n", "training_launch_resp = requests.post(WML_SERVICES_URL + \"/ml/v4/trainings\", \n", " headers={\"Content-Type\": \"application/json\",\n", " \"Authorization\": token},\n", " data=training_payload,\n", " verify=False)\n", "\n", "print(training_launch_resp)\n", "print(\"Launch training response %s\" % training_launch_resp.content.decode(\"utf-8\"))\n", "training_id = json.loads(training_launch_resp.content.decode(\"utf-8\"))[\"metadata\"][\"id\"]\n", "print(\"Training ID: %s\" % training_id)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 4.1 トレーニングジョブのステータス取得" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "status_full = requests.get(WML_SERVICES_URL + \"/ml/v4/trainings/\" + training_id,\n", " headers={\"Content-Type\": \"application/json\",\n", " \"Authorization\": token},\n", " params={\"version\": API_VERSION,\n", " \"project_id\": PROJECT_ID},\n", " verify=False)\n", "\n", "print(status_full)\n", "status_json = json.loads(status_full.content.decode(\"utf-8\"))\n", "print(\"Full training job status: \"+ json.dumps(status_json, indent=4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### アグリゲータのステータスが受け入れ側になるのを待つ" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
先に進む前に、前のセルを実行します。 \n", "出力は `accepting_parties` であるはずです。 \n", "出力が `pending` の場合は、数分待ってから previous のコードセルを requests.get で再実行して、このコードセルを再実行して出力を確認してください。
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 変数を取得し、パーティーのノートブックに貼り付け\n", "\n", "以下のセルを実行し、出力をコピーします。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"WML_SERVICES_HOST = '%s'\" % WML_SERVICES_HOST)\n", "print(\"IAM_APIKEY = '%s'\" % IAM_APIKEY)\n", "print(\"RTS_ID = '%s'\" % wml_remote_training_system_one_asset_uid)\n", "print(\"TRAINING_ID = '%s'\" % (training_id))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "管理者として、あなたは今、Federated Learningの実験を開始しました。 \n", "前のセルの出力をコピーします。 \n", "Part 2 - WML Federated Learning with MNIST for Partyを開き、最初のコードセルに出力を貼り付けてください。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " \n", "## まとめ\n", "\n", "おめでとう!あなたは以下のことを学びました。\n", "\n", "1. Fedareted Learningの実験を開始する\n", "2. テンプレートモデルを読み込む\n", "3. RTSを作成し、実験ジョブを起動する\n", "4. 学習用のデータセットをロードする\n", "5. データハンドラの定義\n", "6. パーティーを設定する\n", "7. アグリゲータに接続する\n", "8. Federated Learningモデルをトレーニングする\n", "\n", "### もっと詳しく知りたい方はこちら\n", "\n", "- Federated Learningの設定、用語、UIからのFederated Learningの実行についての詳細は、Federated Learning documentation for Cloudを参照してください。\n", "- Kerasのモデルテンプレートの詳細については、こちらを参照してください。\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" } }, "nbformat": 4, "nbformat_minor": 1 }