メインコンテンツまでスキップ

Databricks で Ray クラスターを開始する

Databricks は、 Apache Spark ジョブの場合と同じようにクラスターとジョブ設定を処理することで、Ray クラスターの開始プロセスを簡素化します。 これは、Ray クラスターが実際にはマネージド クラスターの Apache Spark 上で開始されるためです。

Databricksでレイを実行する

Python
from ray.util.spark import setup_ray_cluster
import ray

# If the cluster has four workers with 8 CPUs each as an example
setup_ray_cluster(num_worker_nodes=4, num_cpus_per_worker=8)

# Pass any custom configuration to ray.init
ray.init(ignore_reinit_error=True)

このアプローチは、数ノードから数百ノードまで、あらゆるクラスター規模で機能します。 Databricksの Ray クラスターは、オートスケールもサポートしています。

Ray クラスターを作成した後は、 Databricks ノートブックで任意の Ray アプリケーションコードを実行できます。

important

Databricks では、アプリケーションに必要なライブラリを %pip install <your-library-dependency> とともにインストールし、それらを Ray クラスターおよびアプリケーションで使用できるようにすることをお勧めします。 Ray init 関数呼び出しで依存関係を指定すると、Apache Spark ワーカー ノードからアクセスできない場所に依存関係がインストールされるため、バージョンの非互換性とインポート エラーが発生します。

たとえば、次のように Databricks ノートブックで単純な Ray アプリケーションを実行できます。

Python
import ray
import random
import time
from fractions import Fraction

ray.init()

@ray.remote
def pi4_sample(sample_count):
"""pi4_sample runs sample_count experiments, and returns the
fraction of time it was inside the circle.
"""
in_count = 0
for i in range(sample_count):
x = random.random()
y = random.random()
if x*x + y*y <= 1:
in_count += 1
return Fraction(in_count, sample_count)

SAMPLE_COUNT = 1000 * 1000
start = time.time()
future = pi4_sample.remote(sample_count=SAMPLE_COUNT)
pi4 = ray.get(future)
end = time.time()
dur = end - start
print(f'Running {SAMPLE_COUNT} tests took {dur} seconds')

pi = pi4 * 4
print(float(pi))

Ray クラスターのシャットダウン

Ray クラスターは、次の状況で自動的にシャットダウンします。

  • インタラクティブノートブックを Databricks クラスターから切り離します。
  • Databricks ジョブが完了しました。
  • Databricks クラスターが再起動または終了しました。
  • 指定されたアイドル時間にはアクティビティはありません。

Databricksで実行されている Ray クラスターをシャットダウンするには、ray.utils.spark.shutdown_ray_cluster APIを呼び出します。

Python
from ray.utils.spark import shutdown_ray_cluster
import ray

shutdown_ray_cluster()
ray.shutdown()

次のステップ