From b06ea19a728a68804bcd5fd722f3b6c419a7a637 Mon Sep 17 00:00:00 2001 From: Mustafa Eyceoz Date: Tue, 1 Aug 2023 17:39:52 -0400 Subject: [PATCH 1/4] Changed min/max workers to single field --- src/codeflare_sdk/cluster/cluster.py | 11 +- src/codeflare_sdk/cluster/config.py | 3 +- src/codeflare_sdk/cluster/model.py | 3 +- src/codeflare_sdk/job/jobs.py | 2 +- src/codeflare_sdk/utils/pretty_print.py | 9 +- tests/unit_test.py | 162 ++++++++++++------------ 6 files changed, 90 insertions(+), 100 deletions(-) diff --git a/src/codeflare_sdk/cluster/cluster.py b/src/codeflare_sdk/cluster/cluster.py index a1afc1580..319ccdeb6 100644 --- a/src/codeflare_sdk/cluster/cluster.py +++ b/src/codeflare_sdk/cluster/cluster.py @@ -83,7 +83,7 @@ def create_app_wrapper(self): min_memory = self.config.min_memory max_memory = self.config.max_memory gpu = self.config.gpu - workers = self.config.max_worker + workers = self.config.worker template = self.config.template image = self.config.image instascale = self.config.instascale @@ -318,8 +318,7 @@ def from_k8_cluster_object(rc): name=rc["metadata"]["name"], namespace=rc["metadata"]["namespace"], machine_types=machine_types, - min_worker=rc["spec"]["workerGroupSpecs"][0]["minReplicas"], - max_worker=rc["spec"]["workerGroupSpecs"][0]["maxReplicas"], + worker=rc["spec"]["workerGroupSpecs"][0]["minReplicas"], min_cpus=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ "containers" ][0]["resources"]["requests"]["cpu"], @@ -545,8 +544,7 @@ def _map_to_ray_cluster(rc) -> Optional[RayCluster]: name=rc["metadata"]["name"], status=status, # for now we are not using autoscaling so same replicas is fine - min_workers=rc["spec"]["workerGroupSpecs"][0]["replicas"], - max_workers=rc["spec"]["workerGroupSpecs"][0]["replicas"], + workers=rc["spec"]["workerGroupSpecs"][0]["replicas"], worker_mem_max=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ "containers" ][0]["resources"]["limits"]["memory"], @@ -575,8 +573,7 @@ def _copy_to_ray(cluster: Cluster) -> RayCluster: ray = RayCluster( name=cluster.config.name, status=cluster.status(print_to_console=False)[0], - min_workers=cluster.config.min_worker, - max_workers=cluster.config.max_worker, + workers=cluster.config.worker, worker_mem_min=cluster.config.min_memory, worker_mem_max=cluster.config.max_memory, worker_cpu=cluster.config.min_cpus, diff --git a/src/codeflare_sdk/cluster/config.py b/src/codeflare_sdk/cluster/config.py index 31f70d6b9..de6067854 100644 --- a/src/codeflare_sdk/cluster/config.py +++ b/src/codeflare_sdk/cluster/config.py @@ -37,8 +37,7 @@ class ClusterConfiguration: machine_types: list = field(default_factory=list) # ["m4.xlarge", "g4dn.xlarge"] min_cpus: int = 1 max_cpus: int = 1 - min_worker: int = 1 - max_worker: int = 1 + worker: int = 1 min_memory: int = 2 max_memory: int = 2 gpu: int = 0 diff --git a/src/codeflare_sdk/cluster/model.py b/src/codeflare_sdk/cluster/model.py index 9f034da9d..0f031995a 100644 --- a/src/codeflare_sdk/cluster/model.py +++ b/src/codeflare_sdk/cluster/model.py @@ -67,8 +67,7 @@ class RayCluster: name: str status: RayClusterStatus - min_workers: int - max_workers: int + workers: int worker_mem_min: str worker_mem_max: str worker_cpu: int diff --git a/src/codeflare_sdk/job/jobs.py b/src/codeflare_sdk/job/jobs.py index b1db70d54..234e19fa3 100644 --- a/src/codeflare_sdk/job/jobs.py +++ b/src/codeflare_sdk/job/jobs.py @@ -91,7 +91,7 @@ def __init__( self.workspace = workspace def _dry_run(self, cluster: "Cluster"): - j = f"{cluster.config.max_worker}x{max(cluster.config.gpu, 1)}" # # of proc. = # of gpus + j = f"{cluster.config.worker}x{max(cluster.config.gpu, 1)}" # # of proc. = # of gpus return torchx_runner.dryrun( app=ddp( *self.script_args, diff --git a/src/codeflare_sdk/utils/pretty_print.py b/src/codeflare_sdk/utils/pretty_print.py index 0fd17e610..b61b54203 100644 --- a/src/codeflare_sdk/utils/pretty_print.py +++ b/src/codeflare_sdk/utils/pretty_print.py @@ -115,8 +115,7 @@ def print_clusters(clusters: List[RayCluster]): ) name = cluster.name dashboard = cluster.dashboard - mincount = str(cluster.min_workers) - maxcount = str(cluster.max_workers) + workers = str(cluster.workers) memory = str(cluster.worker_mem_min) + "~" + str(cluster.worker_mem_max) cpu = str(cluster.worker_cpu) gpu = str(cluster.worker_gpu) @@ -142,10 +141,10 @@ def print_clusters(clusters: List[RayCluster]): #'table1' to display the worker counts table1 = Table(box=None) table1.add_row() - table1.add_column("Min", style="cyan", no_wrap=True) - table1.add_column("Max", style="magenta") + # table1.add_column("Min", style="cyan", no_wrap=True) + table1.add_column("# Workers", style="magenta") table1.add_row() - table1.add_row(mincount, maxcount) + table1.add_row(workers) table1.add_row() #'table2' to display the worker resources diff --git a/tests/unit_test.py b/tests/unit_test.py index 37aca2026..12a376359 100644 --- a/tests/unit_test.py +++ b/tests/unit_test.py @@ -173,8 +173,7 @@ def test_config_creation(): config = ClusterConfiguration( name="unit-test-cluster", namespace="ns", - min_worker=1, - max_worker=2, + worker=2, min_cpus=3, max_cpus=4, min_memory=5, @@ -186,7 +185,7 @@ def test_config_creation(): ) assert config.name == "unit-test-cluster" and config.namespace == "ns" - assert config.min_worker == 1 and config.max_worker == 2 + assert config.worker == 2 assert config.min_cpus == 3 and config.max_cpus == 4 assert config.min_memory == 5 and config.max_memory == 6 assert config.gpu == 7 @@ -459,8 +458,7 @@ def test_ray_details(mocker, capsys): ray1 = RayCluster( name="raytest1", status=RayClusterStatus.READY, - min_workers=1, - max_workers=1, + workers=1, worker_mem_min=2, worker_mem_max=2, worker_cpu=1, @@ -483,8 +481,7 @@ def test_ray_details(mocker, capsys): assert details == ray2 assert ray2.name == "raytest2" assert ray1.namespace == ray2.namespace - assert ray1.min_workers == ray2.min_workers - assert ray1.max_workers == ray2.max_workers + assert ray1.workers == ray2.workers assert ray1.worker_mem_min == ray2.worker_mem_min assert ray1.worker_mem_max == ray2.worker_mem_max assert ray1.worker_cpu == ray2.worker_cpu @@ -497,58 +494,58 @@ def test_ray_details(mocker, capsys): assert 0 == 1 captured = capsys.readouterr() assert captured.out == ( - " ๐Ÿš€ CodeFlare Cluster Details ๐Ÿš€ \n" - " \n" - " โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ \n" - " โ”‚ Name โ”‚ \n" - " โ”‚ raytest2 Inactive โŒ โ”‚ \n" - " โ”‚ โ”‚ \n" - " โ”‚ URI: ray://raytest2-head-svc.ns.svc:10001 โ”‚ \n" - " โ”‚ โ”‚ \n" - " โ”‚ Dashboard๐Ÿ”— โ”‚ \n" - " โ”‚ โ”‚ \n" - " โ”‚ Cluster Resources โ”‚ \n" - " โ”‚ โ•ญโ”€ Workers โ”€โ”€โ•ฎ โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Worker specs(each) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ \n" - " โ”‚ โ”‚ Min Max โ”‚ โ”‚ Memory CPU GPU โ”‚ โ”‚ \n" - " โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ \n" - " โ”‚ โ”‚ 1 1 โ”‚ โ”‚ 2~2 1 0 โ”‚ โ”‚ \n" - " โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ \n" - " โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ”‚ \n" - " โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ \n" - " ๐Ÿš€ CodeFlare Cluster Details ๐Ÿš€ \n" - " \n" - " โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ \n" - " โ”‚ Name โ”‚ \n" - " โ”‚ raytest1 Active โœ… โ”‚ \n" - " โ”‚ โ”‚ \n" - " โ”‚ URI: ray://raytest1-head-svc.ns.svc:10001 โ”‚ \n" - " โ”‚ โ”‚ \n" - " โ”‚ Dashboard๐Ÿ”— โ”‚ \n" - " โ”‚ โ”‚ \n" - " โ”‚ Cluster Resources โ”‚ \n" - " โ”‚ โ•ญโ”€ Workers โ”€โ”€โ•ฎ โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Worker specs(each) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ \n" - " โ”‚ โ”‚ Min Max โ”‚ โ”‚ Memory CPU GPU โ”‚ โ”‚ \n" - " โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ \n" - " โ”‚ โ”‚ 1 1 โ”‚ โ”‚ 2~2 1 0 โ”‚ โ”‚ \n" - " โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ \n" - " โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ”‚ \n" - " โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ \n" - "โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ\n" - "โ”‚ Name โ”‚\n" - "โ”‚ raytest2 Inactive โŒ โ”‚\n" - "โ”‚ โ”‚\n" - "โ”‚ URI: ray://raytest2-head-svc.ns.svc:10001 โ”‚\n" - "โ”‚ โ”‚\n" - "โ”‚ Dashboard๐Ÿ”— โ”‚\n" - "โ”‚ โ”‚\n" - "โ”‚ Cluster Resources โ”‚\n" - "โ”‚ โ•ญโ”€ Workers โ”€โ”€โ•ฎ โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Worker specs(each) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚\n" - "โ”‚ โ”‚ Min Max โ”‚ โ”‚ Memory CPU GPU โ”‚ โ”‚\n" - "โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚\n" - "โ”‚ โ”‚ 1 1 โ”‚ โ”‚ 2~2 1 0 โ”‚ โ”‚\n" - "โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚\n" - "โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ”‚\n" - "โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ\n" + " ๐Ÿš€ CodeFlare Cluster Details ๐Ÿš€ \n" + " \n" + " โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ \n" + " โ”‚ Name โ”‚ \n" + " โ”‚ raytest2 Inactive โŒ โ”‚ \n" + " โ”‚ โ”‚ \n" + " โ”‚ URI: ray://raytest2-head-svc.ns.svc:10001 โ”‚ \n" + " โ”‚ โ”‚ \n" + " โ”‚ Dashboard๐Ÿ”— โ”‚ \n" + " โ”‚ โ”‚ \n" + " โ”‚ Cluster Resources โ”‚ \n" + " โ”‚ โ•ญโ”€โ”€ Workers โ”€โ”€โ•ฎ โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Worker specs(each) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ \n" + " โ”‚ โ”‚ # Workers โ”‚ โ”‚ Memory CPU GPU โ”‚ โ”‚ \n" + " โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ \n" + " โ”‚ โ”‚ 1 โ”‚ โ”‚ 2~2 1 0 โ”‚ โ”‚ \n" + " โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ \n" + " โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ”‚ \n" + " โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ \n" + " ๐Ÿš€ CodeFlare Cluster Details ๐Ÿš€ \n" + " \n" + " โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ \n" + " โ”‚ Name โ”‚ \n" + " โ”‚ raytest1 Active โœ… โ”‚ \n" + " โ”‚ โ”‚ \n" + " โ”‚ URI: ray://raytest1-head-svc.ns.svc:10001 โ”‚ \n" + " โ”‚ โ”‚ \n" + " โ”‚ Dashboard๐Ÿ”— โ”‚ \n" + " โ”‚ โ”‚ \n" + " โ”‚ Cluster Resources โ”‚ \n" + " โ”‚ โ•ญโ”€โ”€ Workers โ”€โ”€โ•ฎ โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Worker specs(each) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ \n" + " โ”‚ โ”‚ # Workers โ”‚ โ”‚ Memory CPU GPU โ”‚ โ”‚ \n" + " โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ \n" + " โ”‚ โ”‚ 1 โ”‚ โ”‚ 2~2 1 0 โ”‚ โ”‚ \n" + " โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ \n" + " โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ”‚ \n" + " โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ \n" + "โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ\n" + "โ”‚ Name โ”‚\n" + "โ”‚ raytest2 Inactive โŒ โ”‚\n" + "โ”‚ โ”‚\n" + "โ”‚ URI: ray://raytest2-head-svc.ns.svc:10001 โ”‚\n" + "โ”‚ โ”‚\n" + "โ”‚ Dashboard๐Ÿ”— โ”‚\n" + "โ”‚ โ”‚\n" + "โ”‚ Cluster Resources โ”‚\n" + "โ”‚ โ•ญโ”€โ”€ Workers โ”€โ”€โ•ฎ โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Worker specs(each) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚\n" + "โ”‚ โ”‚ # Workers โ”‚ โ”‚ Memory CPU GPU โ”‚ โ”‚\n" + "โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚\n" + "โ”‚ โ”‚ 1 โ”‚ โ”‚ 2~2 1 0 โ”‚ โ”‚\n" + "โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚\n" + "โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ”‚\n" + "โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ\n" " ๐Ÿš€ CodeFlare Cluster Status ๐Ÿš€ \n" " \n" " โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ \n" @@ -1534,7 +1531,7 @@ def test_get_cluster(mocker): cluster_config.image == "ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103" ) - assert cluster_config.min_worker == 1 and cluster_config.max_worker == 1 + assert cluster_config.worker == 1 def test_list_clusters(mocker, capsys): @@ -1557,24 +1554,24 @@ def test_list_clusters(mocker, capsys): list_all_clusters("ns") captured = capsys.readouterr() assert captured.out == ( - " ๐Ÿš€ CodeFlare Cluster Details ๐Ÿš€ \n" - " \n" - " โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ \n" - " โ”‚ Name โ”‚ \n" - " โ”‚ quicktest Active โœ… โ”‚ \n" - " โ”‚ โ”‚ \n" - " โ”‚ URI: ray://quicktest-head-svc.ns.svc:10001 โ”‚ \n" - " โ”‚ โ”‚ \n" - " โ”‚ Dashboard๐Ÿ”— โ”‚ \n" - " โ”‚ โ”‚ \n" - " โ”‚ Cluster Resources โ”‚ \n" - " โ”‚ โ•ญโ”€ Workers โ”€โ”€โ•ฎ โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Worker specs(each) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ \n" - " โ”‚ โ”‚ Min Max โ”‚ โ”‚ Memory CPU GPU โ”‚ โ”‚ \n" - " โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ \n" - " โ”‚ โ”‚ 1 1 โ”‚ โ”‚ 2G~2G 1 0 โ”‚ โ”‚ \n" - " โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ \n" - " โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ”‚ \n" - " โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ \n" + " ๐Ÿš€ CodeFlare Cluster Details ๐Ÿš€ \n" + " \n" + " โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ \n" + " โ”‚ Name โ”‚ \n" + " โ”‚ quicktest Active โœ… โ”‚ \n" + " โ”‚ โ”‚ \n" + " โ”‚ URI: ray://quicktest-head-svc.ns.svc:10001 โ”‚ \n" + " โ”‚ โ”‚ \n" + " โ”‚ Dashboard๐Ÿ”— โ”‚ \n" + " โ”‚ โ”‚ \n" + " โ”‚ Cluster Resources โ”‚ \n" + " โ”‚ โ•ญโ”€โ”€ Workers โ”€โ”€โ•ฎ โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Worker specs(each) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ \n" + " โ”‚ โ”‚ # Workers โ”‚ โ”‚ Memory CPU GPU โ”‚ โ”‚ \n" + " โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ \n" + " โ”‚ โ”‚ 1 โ”‚ โ”‚ 2G~2G 1 0 โ”‚ โ”‚ \n" + " โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ \n" + " โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ”‚ \n" + " โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ \n" ) @@ -1621,8 +1618,7 @@ def test_cluster_status(mocker): fake_ray = RayCluster( name="test", status=RayClusterStatus.UNKNOWN, - min_workers=1, - max_workers=1, + workers=1, worker_mem_min=2, worker_mem_max=2, worker_cpu=1, @@ -1872,7 +1868,7 @@ def test_DDPJobDefinition_dry_run_no_resource_args(mocker): assert ddp_job._app.roles[0].resource.memMB == cluster.config.max_memory * 1024 assert ( parse_j(ddp_job._app.roles[0].args[1]) - == f"{cluster.config.max_worker}x{cluster.config.gpu}" + == f"{cluster.config.worker}x{cluster.config.gpu}" ) @@ -2064,9 +2060,9 @@ def parse_j(cmd): else: return None args = substring.split() - max_worker = args[1] + worker = args[1] gpu = args[3] - return f"{max_worker}x{gpu}" + return f"{worker}x{gpu}" def test_AWManager_creation(): From 6e577863b8cdca7c8446703910a75334bed1edf5 Mon Sep 17 00:00:00 2001 From: Mustafa Eyceoz Date: Thu, 3 Aug 2023 14:54:09 -0400 Subject: [PATCH 2/4] Updated to num_workers, num_gpus, and demo update --- .../preview_nbs/0_basic_ray.ipynb | 201 ++++++++++++ .../preview_nbs/1_basic_instascale.ipynb | 172 ++++++++++ .../preview_nbs/2_basic_jobs.ipynb | 288 +++++++++++++++++ .../preview_nbs/3_basic_interactive.ipynb | 301 ++++++++++++++++++ .../guided-demos/preview_nbs/4_gpt.ipynb | 190 +++++++++++ src/codeflare_sdk/cluster/cluster.py | 18 +- src/codeflare_sdk/cluster/config.py | 4 +- src/codeflare_sdk/job/jobs.py | 4 +- tests/unit_test.py | 16 +- 9 files changed, 1173 insertions(+), 21 deletions(-) create mode 100644 demo-notebooks/guided-demos/preview_nbs/0_basic_ray.ipynb create mode 100644 demo-notebooks/guided-demos/preview_nbs/1_basic_instascale.ipynb create mode 100644 demo-notebooks/guided-demos/preview_nbs/2_basic_jobs.ipynb create mode 100644 demo-notebooks/guided-demos/preview_nbs/3_basic_interactive.ipynb create mode 100644 demo-notebooks/guided-demos/preview_nbs/4_gpt.ipynb diff --git a/demo-notebooks/guided-demos/preview_nbs/0_basic_ray.ipynb b/demo-notebooks/guided-demos/preview_nbs/0_basic_ray.ipynb new file mode 100644 index 000000000..7eec08028 --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/0_basic_ray.ipynb @@ -0,0 +1,201 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "8d4a42f6", + "metadata": {}, + "source": [ + "In this first notebook, we will go through the basics of using the SDK to:\n", + " - Spin up a Ray cluster with our desired resources\n", + " - View the status and specs of our Ray cluster\n", + " - Take down the Ray cluster when finished" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b55bc3ea-4ce3-49bf-bb1f-e209de8ca47a", + "metadata": {}, + "outputs": [], + "source": [ + "# Import pieces from codeflare-sdk\n", + "from codeflare_sdk.cluster.cluster import Cluster, ClusterConfiguration\n", + "from codeflare_sdk.cluster.auth import TokenAuthentication" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "614daa0c", + "metadata": {}, + "outputs": [], + "source": [ + "# Create authentication object for oc user permissions\n", + "auth = TokenAuthentication(\n", + " token = \"XXXXX\",\n", + " server = \"XXXXX\",\n", + " skip_tls=False\n", + ")\n", + "auth.login()" + ] + }, + { + "cell_type": "markdown", + "id": "bc27f84c", + "metadata": {}, + "source": [ + "Here, we want to define our cluster by specifying the resources we require for our batch workload. Below, we define our cluster object (which generates a corresponding AppWrapper)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0f4bc870-091f-4e11-9642-cba145710159", + "metadata": {}, + "outputs": [], + "source": [ + "# Create and configure our cluster object (and appwrapper)\n", + "cluster = Cluster(ClusterConfiguration(\n", + " name='raytest',\n", + " namespace='default',\n", + " num_workers=2,\n", + " min_cpus=1,\n", + " max_cpus=1,\n", + " min_memory=4,\n", + " max_memory=4,\n", + " num_gpus=0,\n", + " instascale=False\n", + "))" + ] + }, + { + "cell_type": "markdown", + "id": "12eef53c", + "metadata": {}, + "source": [ + "Next, we want to bring our cluster up, so we call the `up()` function below to submit our cluster AppWrapper yaml onto the MCAD queue, and begin the process of obtaining our resource cluster." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f0884bbc-c224-4ca0-98a0-02dfa09c2200", + "metadata": {}, + "outputs": [], + "source": [ + "# Bring up the cluster\n", + "cluster.up()" + ] + }, + { + "cell_type": "markdown", + "id": "657ebdfb", + "metadata": {}, + "source": [ + "Now, we want to check on the status of our resource cluster, and wait until it is finally ready for use." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3c1b4311-2e61-44c9-8225-87c2db11363d", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.status()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a99d5aff", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.wait_ready()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "df71c1ed", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.status()" + ] + }, + { + "cell_type": "markdown", + "id": "b3a55fe4", + "metadata": {}, + "source": [ + "Let's quickly verify that the specs of the cluster are as expected." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7fd45bc5-03c0-4ae5-9ec5-dd1c30f1a084", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.details()" + ] + }, + { + "cell_type": "markdown", + "id": "5af8cd32", + "metadata": {}, + "source": [ + "Finally, we bring our resource cluster down and release/terminate the associated resources, bringing everything back to the way it was before our cluster was brought up." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5f36db0f-31f6-4373-9503-dc3c1c4c3f57", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.down()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0d41b90e", + "metadata": {}, + "outputs": [], + "source": [ + "auth.logout()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "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.8.13" + }, + "vscode": { + "interpreter": { + "hash": "f9f85f796d01129d0dd105a088854619f454435301f6ffec2fea96ecbd9be4ac" + } + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/demo-notebooks/guided-demos/preview_nbs/1_basic_instascale.ipynb b/demo-notebooks/guided-demos/preview_nbs/1_basic_instascale.ipynb new file mode 100644 index 000000000..8f8a6ed73 --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/1_basic_instascale.ipynb @@ -0,0 +1,172 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "9865ee8c", + "metadata": {}, + "source": [ + "In this second notebook, we will go over the basics of using InstaScale to scale up/down necessary resources that are not currently available on your OpenShift Cluster (in cloud environments)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b55bc3ea-4ce3-49bf-bb1f-e209de8ca47a", + "metadata": {}, + "outputs": [], + "source": [ + "# Import pieces from codeflare-sdk\n", + "from codeflare_sdk.cluster.cluster import Cluster, ClusterConfiguration\n", + "from codeflare_sdk.cluster.auth import TokenAuthentication" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "614daa0c", + "metadata": {}, + "outputs": [], + "source": [ + "# Create authentication object for oc user permissions\n", + "auth = TokenAuthentication(\n", + " token = \"XXXXX\",\n", + " server = \"XXXXX\",\n", + " skip_tls=False\n", + ")\n", + "auth.login()" + ] + }, + { + "cell_type": "markdown", + "id": "bc27f84c", + "metadata": {}, + "source": [ + "This time, we are working in a cloud environment, and our OpenShift cluster does not have the resources needed for our desired workloads. We will use InstaScale to dynamically scale-up guaranteed resources based on our request (that will also automatically scale-down when we are finished working):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0f4bc870-091f-4e11-9642-cba145710159", + "metadata": {}, + "outputs": [], + "source": [ + "# Create and configure our cluster object (and appwrapper)\n", + "cluster = Cluster(ClusterConfiguration(\n", + " name='instascaletest',\n", + " namespace='default',\n", + " num_workers=2,\n", + " min_cpus=2,\n", + " max_cpus=2,\n", + " min_memory=8,\n", + " max_memory=8,\n", + " num_gpus=1,\n", + " instascale=True, # InstaScale now enabled, will scale OCP cluster to guarantee resource request\n", + " machine_types=[\"m5.xlarge\", \"g4dn.xlarge\"] # Head, worker AWS machine types desired\n", + "))" + ] + }, + { + "cell_type": "markdown", + "id": "12eef53c", + "metadata": {}, + "source": [ + "Same as last time, we will bring the cluster up, wait for it to be ready, and confirm that the specs are as-requested:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f0884bbc-c224-4ca0-98a0-02dfa09c2200", + "metadata": {}, + "outputs": [], + "source": [ + "# Bring up the cluster\n", + "cluster.up()\n", + "cluster.wait_ready()" + ] + }, + { + "cell_type": "markdown", + "id": "6abfe904", + "metadata": {}, + "source": [ + "While the resources are being scaled, we can also go into the console and take a look at the InstaScale logs, as well as the new machines/nodes spinning up.\n", + "\n", + "Once the cluster is ready, we can confirm the specs:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7fd45bc5-03c0-4ae5-9ec5-dd1c30f1a084", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.details()" + ] + }, + { + "cell_type": "markdown", + "id": "5af8cd32", + "metadata": {}, + "source": [ + "Finally, we bring our resource cluster down and release/terminate the associated resources, bringing everything back to the way it was before our cluster was brought up." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5f36db0f-31f6-4373-9503-dc3c1c4c3f57", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.down()" + ] + }, + { + "cell_type": "markdown", + "id": "c883caea", + "metadata": {}, + "source": [ + "Once again, we can look at the machines/nodes and see that everything has been successfully scaled down!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0d41b90e", + "metadata": {}, + "outputs": [], + "source": [ + "auth.logout()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "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.8.13" + }, + "vscode": { + "interpreter": { + "hash": "f9f85f796d01129d0dd105a088854619f454435301f6ffec2fea96ecbd9be4ac" + } + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/demo-notebooks/guided-demos/preview_nbs/2_basic_jobs.ipynb b/demo-notebooks/guided-demos/preview_nbs/2_basic_jobs.ipynb new file mode 100644 index 000000000..eb9247153 --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/2_basic_jobs.ipynb @@ -0,0 +1,288 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "464af595", + "metadata": {}, + "source": [ + "In this third notebook, we will go over the basics of submitting jobs via the SDK, either to a Ray cluster or directly to MCAD." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b55bc3ea-4ce3-49bf-bb1f-e209de8ca47a", + "metadata": {}, + "outputs": [], + "source": [ + "# Import pieces from codeflare-sdk\n", + "from codeflare_sdk.cluster.cluster import Cluster, ClusterConfiguration\n", + "from codeflare_sdk.cluster.auth import TokenAuthentication" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "614daa0c", + "metadata": {}, + "outputs": [], + "source": [ + "# Create authentication object for oc user permissions\n", + "auth = TokenAuthentication(\n", + " token = \"XXXXX\",\n", + " server = \"XXXXX\",\n", + " skip_tls=False\n", + ")\n", + "auth.login()" + ] + }, + { + "cell_type": "markdown", + "id": "bc27f84c", + "metadata": {}, + "source": [ + "Let's start by running through the same cluster setup as before:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0f4bc870-091f-4e11-9642-cba145710159", + "metadata": {}, + "outputs": [], + "source": [ + "# Create and configure our cluster object (and appwrapper)\n", + "cluster = Cluster(ClusterConfiguration(\n", + " name='jobtest',\n", + " namespace='default',\n", + " num_workers=2,\n", + " min_cpus=1,\n", + " max_cpus=1,\n", + " min_memory=4,\n", + " max_memory=4,\n", + " num_gpus=0,\n", + " instascale=False\n", + "))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f0884bbc-c224-4ca0-98a0-02dfa09c2200", + "metadata": {}, + "outputs": [], + "source": [ + "# Bring up the cluster\n", + "cluster.up()\n", + "cluster.wait_ready()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "df71c1ed", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.details()" + ] + }, + { + "cell_type": "markdown", + "id": "33663f47", + "metadata": {}, + "source": [ + "This time, however, we are going to use the CodeFlare SDK to submit batch jobs via TorchX, either to the Ray cluster we have just brought up, or directly to MCAD." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c7b4f232", + "metadata": {}, + "outputs": [], + "source": [ + "from codeflare_sdk.job.jobs import DDPJobDefinition" + ] + }, + { + "cell_type": "markdown", + "id": "83d77b74", + "metadata": {}, + "source": [ + "First, let's begin by submitting to Ray, training a basic NN on the MNIST dataset:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8c2c5138", + "metadata": {}, + "outputs": [], + "source": [ + "jobdef = DDPJobDefinition(\n", + " name=\"mnisttest\",\n", + " script=\"mnist.py\",\n", + " scheduler_args={\"requirements\": \"requirements.txt\"}\n", + ")\n", + "job = jobdef.submit(cluster)" + ] + }, + { + "cell_type": "markdown", + "id": "5b9ae53a", + "metadata": {}, + "source": [ + "Now we can take a look at the status of our submitted job, as well as the logs:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6e36c3d9", + "metadata": {}, + "outputs": [], + "source": [ + "job.status()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "834cfb5c", + "metadata": {}, + "outputs": [], + "source": [ + "job.logs()" + ] + }, + { + "cell_type": "markdown", + "id": "5af8cd32", + "metadata": {}, + "source": [ + "Once complete, we can bring our Ray cluster down and clean up:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5f36db0f-31f6-4373-9503-dc3c1c4c3f57", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.down()" + ] + }, + { + "cell_type": "markdown", + "id": "31096641", + "metadata": {}, + "source": [ + "Now, an alternative option for job submission is to submit directly to MCAD, which will schedule pods to run the job with requested resources:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "496139cc", + "metadata": {}, + "outputs": [], + "source": [ + "jobdef = DDPJobDefinition(\n", + " name=\"mnistjob\",\n", + " script=\"mnist.py\",\n", + " scheduler_args={\"namespace\": \"default\"},\n", + " j=\"1x1\",\n", + " gpu=0,\n", + " cpu=1,\n", + " memMB=8000,\n", + " image=\"quay.io/project-codeflare/mnist-job-test:v0.0.1\"\n", + ")\n", + "job = jobdef.submit()" + ] + }, + { + "cell_type": "markdown", + "id": "0837e43b", + "metadata": {}, + "source": [ + "Once again, we can look at job status and logs:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3d18d42c", + "metadata": {}, + "outputs": [], + "source": [ + "job.status()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "36d7ea97", + "metadata": {}, + "outputs": [], + "source": [ + "job.logs()" + ] + }, + { + "cell_type": "markdown", + "id": "aebf376a", + "metadata": {}, + "source": [ + "This time, once the pods complete, we can clean them up alongside any other associated resources. The following command can also be used to delete jobs early for both Ray and MCAD submission:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ebbb0674", + "metadata": {}, + "outputs": [], + "source": [ + "job.cancel()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0d41b90e", + "metadata": {}, + "outputs": [], + "source": [ + "auth.logout()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "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.8.13" + }, + "vscode": { + "interpreter": { + "hash": "f9f85f796d01129d0dd105a088854619f454435301f6ffec2fea96ecbd9be4ac" + } + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/demo-notebooks/guided-demos/preview_nbs/3_basic_interactive.ipynb b/demo-notebooks/guided-demos/preview_nbs/3_basic_interactive.ipynb new file mode 100644 index 000000000..73eff977a --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/3_basic_interactive.ipynb @@ -0,0 +1,301 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "bbc21043", + "metadata": {}, + "source": [ + "In this fourth and final notebook, we will go over how to leverage the SDK to directly work interactively with a Ray cluster during development." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b55bc3ea-4ce3-49bf-bb1f-e209de8ca47a", + "metadata": {}, + "outputs": [], + "source": [ + "# Import pieces from codeflare-sdk\n", + "from codeflare_sdk.cluster.cluster import Cluster, ClusterConfiguration\n", + "from codeflare_sdk.cluster.auth import TokenAuthentication" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "614daa0c", + "metadata": {}, + "outputs": [], + "source": [ + "# Create authentication object for oc user permissions\n", + "auth = TokenAuthentication(\n", + " token = \"XXXXX\",\n", + " server = \"XXXXX\",\n", + " skip_tls=False\n", + ")\n", + "auth.login()" + ] + }, + { + "cell_type": "markdown", + "id": "bc27f84c", + "metadata": {}, + "source": [ + "Once again, let's start by running through the same cluster setup as before:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0f4bc870-091f-4e11-9642-cba145710159", + "metadata": {}, + "outputs": [], + "source": [ + "# Create and configure our cluster object (and appwrapper)\n", + "cluster = Cluster(ClusterConfiguration(\n", + " name='interactivetest',\n", + " namespace='default',\n", + " num_workers=2,\n", + " min_cpus=2,\n", + " max_cpus=2,\n", + " min_memory=8,\n", + " max_memory=8,\n", + " num_gpus=1,\n", + " instascale=True,\n", + " machine_types=[\"m5.xlarge\", \"g4dn.xlarge\"]\n", + " \n", + "))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f0884bbc-c224-4ca0-98a0-02dfa09c2200", + "metadata": {}, + "outputs": [], + "source": [ + "# Bring up the cluster\n", + "cluster.up()\n", + "cluster.wait_ready()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "df71c1ed", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.details()" + ] + }, + { + "cell_type": "markdown", + "id": "33663f47", + "metadata": {}, + "source": [ + "This time we will demonstrate another potential method of use: working with the Ray cluster interactively.\n", + "\n", + "Using the SDK, we can get both the Ray cluster URI and dashboard URI:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c1719bca", + "metadata": {}, + "outputs": [], + "source": [ + "ray_dashboard_uri = cluster.cluster_dashboard_uri()\n", + "ray_cluster_uri = cluster.cluster_uri()\n", + "print(ray_dashboard_uri)\n", + "print(ray_cluster_uri)" + ] + }, + { + "cell_type": "markdown", + "id": "2a2aca6a", + "metadata": {}, + "source": [ + "Now we can connect directly to our Ray cluster via the Ray python client:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "300146dc", + "metadata": {}, + "outputs": [], + "source": [ + "#before proceeding make sure the cluster exists and the uri is not empty\n", + "assert ray_cluster_uri, \"Ray cluster needs to be started and set before proceeding\"\n", + "\n", + "import ray\n", + "from ray.air.config import ScalingConfig\n", + "\n", + "# reset the ray context in case there's already one. \n", + "ray.shutdown()\n", + "# establish connection to ray cluster\n", + "\n", + "#install additional libraries that will be required for model training\n", + "runtime_env = {\"pip\": [\"transformers\", \"datasets\", \"evaluate\", \"pyarrow<7.0.0\", \"accelerate\"]}\n", + "\n", + "ray.init(address=f'{ray_cluster_uri}', runtime_env=runtime_env)\n", + "\n", + "print(\"Ray cluster is up and running: \", ray.is_initialized())" + ] + }, + { + "cell_type": "markdown", + "id": "9711030b", + "metadata": {}, + "source": [ + "Now that we are connected (and have passed in some package requirements), let's try writing some training code for a DistilBERT transformer model via HuggingFace (using IMDB dataset):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1b36e0d9", + "metadata": {}, + "outputs": [], + "source": [ + "@ray.remote\n", + "def train_fn():\n", + " from datasets import load_dataset\n", + " import transformers\n", + " from transformers import AutoTokenizer, TrainingArguments\n", + " from transformers import AutoModelForSequenceClassification\n", + " import numpy as np\n", + " from datasets import load_metric\n", + " import ray\n", + " from ray import tune\n", + " from ray.train.huggingface import HuggingFaceTrainer\n", + "\n", + " dataset = load_dataset(\"imdb\")\n", + " tokenizer = AutoTokenizer.from_pretrained(\"distilbert-base-uncased\")\n", + "\n", + " def tokenize_function(examples):\n", + " return tokenizer(examples[\"text\"], padding=\"max_length\", truncation=True)\n", + "\n", + " tokenized_datasets = dataset.map(tokenize_function, batched=True)\n", + "\n", + " #using a fraction of dataset but you can run with the full dataset\n", + " small_train_dataset = tokenized_datasets[\"train\"].shuffle(seed=42).select(range(100))\n", + " small_eval_dataset = tokenized_datasets[\"test\"].shuffle(seed=42).select(range(100))\n", + "\n", + " print(f\"len of train {small_train_dataset} and test {small_eval_dataset}\")\n", + "\n", + " ray_train_ds = ray.data.from_huggingface(small_train_dataset)\n", + " ray_evaluation_ds = ray.data.from_huggingface(small_eval_dataset)\n", + "\n", + " def compute_metrics(eval_pred):\n", + " metric = load_metric(\"accuracy\")\n", + " logits, labels = eval_pred\n", + " predictions = np.argmax(logits, axis=-1)\n", + " return metric.compute(predictions=predictions, references=labels)\n", + "\n", + " def trainer_init_per_worker(train_dataset, eval_dataset, **config):\n", + " model = AutoModelForSequenceClassification.from_pretrained(\"distilbert-base-uncased\", num_labels=2)\n", + "\n", + " training_args = TrainingArguments(\"/tmp/hf_imdb/test\", eval_steps=1, disable_tqdm=True, \n", + " num_train_epochs=1, skip_memory_metrics=True,\n", + " learning_rate=2e-5,\n", + " per_device_train_batch_size=16,\n", + " per_device_eval_batch_size=16, \n", + " weight_decay=0.01,)\n", + " return transformers.Trainer(\n", + " model=model,\n", + " args=training_args,\n", + " train_dataset=train_dataset,\n", + " eval_dataset=eval_dataset,\n", + " compute_metrics=compute_metrics\n", + " )\n", + "\n", + " scaling_config = ScalingConfig(num_workers=2, use_gpu=True) #num workers is the number of gpus\n", + "\n", + " # we are using the ray native HuggingFaceTrainer, but you can swap out to use non ray Huggingface Trainer. Both have the same method signature. \n", + " # the ray native HFTrainer has built in support for scaling to multiple GPUs\n", + " trainer = HuggingFaceTrainer(\n", + " trainer_init_per_worker=trainer_init_per_worker,\n", + " scaling_config=scaling_config,\n", + " datasets={\"train\": ray_train_ds, \"evaluation\": ray_evaluation_ds},\n", + " )\n", + " result = trainer.fit()" + ] + }, + { + "cell_type": "markdown", + "id": "d4d8fd65", + "metadata": {}, + "source": [ + "Once we want to test our code out, we can run the training function we defined above remotely on our Ray cluster:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5901d958", + "metadata": {}, + "outputs": [], + "source": [ + "#call the above cell as a remote ray function\n", + "ray.get(train_fn.remote())" + ] + }, + { + "cell_type": "markdown", + "id": "5af8cd32", + "metadata": {}, + "source": [ + "Once complete, we can bring our Ray cluster down and clean up:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5f36db0f-31f6-4373-9503-dc3c1c4c3f57", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.down()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0d41b90e", + "metadata": {}, + "outputs": [], + "source": [ + "auth.logout()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "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.8.13" + }, + "vscode": { + "interpreter": { + "hash": "f9f85f796d01129d0dd105a088854619f454435301f6ffec2fea96ecbd9be4ac" + } + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/demo-notebooks/guided-demos/preview_nbs/4_gpt.ipynb b/demo-notebooks/guided-demos/preview_nbs/4_gpt.ipynb new file mode 100644 index 000000000..919f8f0a8 --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/4_gpt.ipynb @@ -0,0 +1,190 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "b6c05b69-4ce8-45ef-82d3-bacb2491bee8", + "metadata": {}, + "outputs": [], + "source": [ + "# Import pieces from codeflare-sdk\n", + "from codeflare_sdk.cluster.cluster import Cluster, ClusterConfiguration\n", + "from codeflare_sdk.cluster.auth import TokenAuthentication" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "32f99bbd-9903-4d38-a4f2-223dec684ae2", + "metadata": {}, + "outputs": [], + "source": [ + "# Create authentication object for oc user permissions\n", + "auth = TokenAuthentication(\n", + " token = \"XXXXX\",\n", + " server = \"XXXXX\",\n", + " skip_tls=False\n", + ")\n", + "auth.login()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3f32119a-c4ee-4163-b103-d9ca3bddbdb5", + "metadata": {}, + "outputs": [], + "source": [ + "cluster = Cluster(ClusterConfiguration(\n", + " name='gptfttest',\n", + " namespace='default',\n", + " num_workers=2,\n", + " min_cpus=2,\n", + " max_cpus=2,\n", + " min_memory=8,\n", + " max_memory=8,\n", + " num_gpus=1,\n", + " instascale=True,\n", + " machine_types=[\"m5.xlarge\", \"g4dn.xlarge\"],\n", + "))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "107c8277-3b3b-4238-a786-a391a662fd7c", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.up()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "730f66ce-adaa-4709-b9cf-22417847e059", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.wait_ready()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "48fac218-2f22-428b-9228-137a4bb0e666", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.details()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9ed5bd75-4230-4c7c-a9e2-0f247890e62a", + "metadata": {}, + "outputs": [], + "source": [ + "from codeflare_sdk.job.jobs import DDPJobDefinition" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "611d203a-35aa-4357-a748-1d01b022fcdb", + "metadata": {}, + "outputs": [], + "source": [ + "arg_list = [\n", + " \"--model_name_or_path\", \"gpt2\",\n", + " \"--dataset_name\", \"wikitext\",\n", + " \"--dataset_config_name\", \"wikitext-2-raw-v1\",\n", + " \"--per_device_train_batch_size\", \"2\",\n", + " \"--per_device_eval_batch_size\", \"2\",\n", + " \"--do_train\",\n", + " \"--do_eval\",\n", + " \"--output_dir\", \"/tmp/test-clm\",\n", + " \"--overwrite_output_dir\"\n", + "]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8ac7c34f-e227-44c2-a4b1-a57c853ac3a7", + "metadata": {}, + "outputs": [], + "source": [ + "jobdef = DDPJobDefinition(\n", + " name=\"gpttest\",\n", + " script=\"gpt_og.py\",\n", + " script_args=arg_list,\n", + " scheduler_args={\"requirements\": \"requirements_gpt.txt\"}\n", + ")\n", + "job = jobdef.submit(cluster)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1680d287-de46-45f8-b95a-02ba3c83912c", + "metadata": {}, + "outputs": [], + "source": [ + "job.status()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d25d6198-9941-47e8-857f-9811830cc854", + "metadata": {}, + "outputs": [], + "source": [ + "job.logs()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "beb1a6b9-d9b3-49b7-b036-09f1d3569b59", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.down()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8398d977-db24-46d0-a7d2-b4e9197808d7", + "metadata": {}, + "outputs": [], + "source": [ + "auth.logout()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "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.8.13" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/src/codeflare_sdk/cluster/cluster.py b/src/codeflare_sdk/cluster/cluster.py index 319ccdeb6..c45c50e08 100644 --- a/src/codeflare_sdk/cluster/cluster.py +++ b/src/codeflare_sdk/cluster/cluster.py @@ -82,8 +82,8 @@ def create_app_wrapper(self): max_cpu = self.config.max_cpus min_memory = self.config.min_memory max_memory = self.config.max_memory - gpu = self.config.gpu - workers = self.config.worker + gpu = self.config.num_gpus + workers = self.config.num_workers template = self.config.template image = self.config.image instascale = self.config.instascale @@ -201,7 +201,7 @@ def status( if print_to_console: # overriding the number of gpus with requested - cluster.worker_gpu = self.config.gpu + cluster.worker_gpu = self.config.num_gpus pretty_print.print_cluster_status(cluster) elif print_to_console: if status == CodeFlareClusterStatus.UNKNOWN: @@ -318,7 +318,7 @@ def from_k8_cluster_object(rc): name=rc["metadata"]["name"], namespace=rc["metadata"]["namespace"], machine_types=machine_types, - worker=rc["spec"]["workerGroupSpecs"][0]["minReplicas"], + num_workers=rc["spec"]["workerGroupSpecs"][0]["minReplicas"], min_cpus=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ "containers" ][0]["resources"]["requests"]["cpu"], @@ -335,9 +335,9 @@ def from_k8_cluster_object(rc): "resources" ]["limits"]["memory"][:-1] ), - gpu=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][0][ - "resources" - ]["limits"]["nvidia.com/gpu"], + num_gpus=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["resources"]["limits"]["nvidia.com/gpu"], instascale=True if machine_types else False, image=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][ 0 @@ -573,11 +573,11 @@ def _copy_to_ray(cluster: Cluster) -> RayCluster: ray = RayCluster( name=cluster.config.name, status=cluster.status(print_to_console=False)[0], - workers=cluster.config.worker, + workers=cluster.config.num_workers, worker_mem_min=cluster.config.min_memory, worker_mem_max=cluster.config.max_memory, worker_cpu=cluster.config.min_cpus, - worker_gpu=cluster.config.gpu, + worker_gpu=cluster.config.num_gpus, namespace=cluster.config.namespace, dashboard=cluster.cluster_dashboard_uri(), ) diff --git a/src/codeflare_sdk/cluster/config.py b/src/codeflare_sdk/cluster/config.py index de6067854..aed3674eb 100644 --- a/src/codeflare_sdk/cluster/config.py +++ b/src/codeflare_sdk/cluster/config.py @@ -37,10 +37,10 @@ class ClusterConfiguration: machine_types: list = field(default_factory=list) # ["m4.xlarge", "g4dn.xlarge"] min_cpus: int = 1 max_cpus: int = 1 - worker: int = 1 + num_workers: int = 1 min_memory: int = 2 max_memory: int = 2 - gpu: int = 0 + num_gpus: int = 0 template: str = f"{dir}/templates/base-template.yaml" instascale: bool = False envs: dict = field(default_factory=dict) diff --git a/src/codeflare_sdk/job/jobs.py b/src/codeflare_sdk/job/jobs.py index 234e19fa3..b9bb9cdc1 100644 --- a/src/codeflare_sdk/job/jobs.py +++ b/src/codeflare_sdk/job/jobs.py @@ -91,7 +91,7 @@ def __init__( self.workspace = workspace def _dry_run(self, cluster: "Cluster"): - j = f"{cluster.config.worker}x{max(cluster.config.gpu, 1)}" # # of proc. = # of gpus + j = f"{cluster.config.num_workers}x{max(cluster.config.num_gpus, 1)}" # # of proc. = # of gpus return torchx_runner.dryrun( app=ddp( *self.script_args, @@ -100,7 +100,7 @@ def _dry_run(self, cluster: "Cluster"): name=self.name, h=self.h, cpu=self.cpu if self.cpu is not None else cluster.config.max_cpus, - gpu=self.gpu if self.gpu is not None else cluster.config.gpu, + gpu=self.gpu if self.gpu is not None else cluster.config.num_gpus, memMB=self.memMB if self.memMB is not None else cluster.config.max_memory * 1024, diff --git a/tests/unit_test.py b/tests/unit_test.py index 12a376359..ac126016f 100644 --- a/tests/unit_test.py +++ b/tests/unit_test.py @@ -173,22 +173,22 @@ def test_config_creation(): config = ClusterConfiguration( name="unit-test-cluster", namespace="ns", - worker=2, + num_workers=2, min_cpus=3, max_cpus=4, min_memory=5, max_memory=6, - gpu=7, + num_gpus=7, instascale=True, machine_types=["cpu.small", "gpu.large"], image_pull_secrets=["unit-test-pull-secret"], ) assert config.name == "unit-test-cluster" and config.namespace == "ns" - assert config.worker == 2 + assert config.num_workers == 2 assert config.min_cpus == 3 and config.max_cpus == 4 assert config.min_memory == 5 and config.max_memory == 6 - assert config.gpu == 7 + assert config.num_gpus == 7 assert config.image == "quay.io/project-codeflare/ray:2.5.0-py38-cu116" assert config.template == f"{parent}/src/codeflare_sdk/templates/base-template.yaml" assert config.instascale @@ -1525,13 +1525,13 @@ def test_get_cluster(mocker): ) assert cluster_config.min_cpus == 1 and cluster_config.max_cpus == 1 assert cluster_config.min_memory == 2 and cluster_config.max_memory == 2 - assert cluster_config.gpu == 0 + assert cluster_config.num_gpus == 0 assert cluster_config.instascale assert ( cluster_config.image == "ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103" ) - assert cluster_config.worker == 1 + assert cluster_config.num_workers == 1 def test_list_clusters(mocker, capsys): @@ -1864,11 +1864,11 @@ def test_DDPJobDefinition_dry_run_no_resource_args(mocker): ddp_job = ddp._dry_run(cluster) assert ddp_job._app.roles[0].resource.cpu == cluster.config.max_cpus - assert ddp_job._app.roles[0].resource.gpu == cluster.config.gpu + assert ddp_job._app.roles[0].resource.gpu == cluster.config.num_gpus assert ddp_job._app.roles[0].resource.memMB == cluster.config.max_memory * 1024 assert ( parse_j(ddp_job._app.roles[0].args[1]) - == f"{cluster.config.worker}x{cluster.config.gpu}" + == f"{cluster.config.num_workers}x{cluster.config.num_gpus}" ) From 4987e17995ef0bbf4fce097beed0ded18ed5999d Mon Sep 17 00:00:00 2001 From: Mustafa Eyceoz Date: Thu, 3 Aug 2023 16:16:03 -0400 Subject: [PATCH 3/4] Delete comment on 144 --- src/codeflare_sdk/utils/pretty_print.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/codeflare_sdk/utils/pretty_print.py b/src/codeflare_sdk/utils/pretty_print.py index b61b54203..ca371182c 100644 --- a/src/codeflare_sdk/utils/pretty_print.py +++ b/src/codeflare_sdk/utils/pretty_print.py @@ -141,7 +141,6 @@ def print_clusters(clusters: List[RayCluster]): #'table1' to display the worker counts table1 = Table(box=None) table1.add_row() - # table1.add_column("Min", style="cyan", no_wrap=True) table1.add_column("# Workers", style="magenta") table1.add_row() table1.add_row(workers) From 9b941ca7eff85847fac8045115687d46fb0797a0 Mon Sep 17 00:00:00 2001 From: Mustafa Eyceoz Date: Thu, 3 Aug 2023 18:23:54 -0400 Subject: [PATCH 4/4] Updated preview nbs --- .../preview_nbs/0_basic_ray.ipynb | 1 + .../guided-demos/preview_nbs/gpt_og.py | 728 ++++++++++++++++++ .../guided-demos/preview_nbs/mnist.py | 160 ++++ .../guided-demos/preview_nbs/requirements.txt | 4 + .../preview_nbs/requirements_gpt.txt | 8 + 5 files changed, 901 insertions(+) create mode 100644 demo-notebooks/guided-demos/preview_nbs/gpt_og.py create mode 100644 demo-notebooks/guided-demos/preview_nbs/mnist.py create mode 100644 demo-notebooks/guided-demos/preview_nbs/requirements.txt create mode 100644 demo-notebooks/guided-demos/preview_nbs/requirements_gpt.txt diff --git a/demo-notebooks/guided-demos/preview_nbs/0_basic_ray.ipynb b/demo-notebooks/guided-demos/preview_nbs/0_basic_ray.ipynb index 7eec08028..b3040676f 100644 --- a/demo-notebooks/guided-demos/preview_nbs/0_basic_ray.ipynb +++ b/demo-notebooks/guided-demos/preview_nbs/0_basic_ray.ipynb @@ -64,6 +64,7 @@ " min_memory=4,\n", " max_memory=4,\n", " num_gpus=0,\n", + " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\", #current default\n", " instascale=False\n", "))" ] diff --git a/demo-notebooks/guided-demos/preview_nbs/gpt_og.py b/demo-notebooks/guided-demos/preview_nbs/gpt_og.py new file mode 100644 index 000000000..d69e41fcb --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/gpt_og.py @@ -0,0 +1,728 @@ +#!/usr/bin/env python +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...) on a text file or a dataset. + +Here is the full list of checkpoints on the hub that can be fine-tuned by this script: +https://huggingface.co/models?filter=text-generation +""" +# You can also adapt this script on your own causal language modeling task. Pointers for this are left as comments. + +import subprocess + +subprocess.run(["pip", "uninstall", "protobuf"]) +subprocess.run( + [ + "pip", + "install", + "--upgrade", + "--target=/home/ray/workspace", + "-r", + "requirements.txt", + ] +) + +import logging +import math +import os +import sys +from dataclasses import dataclass, field +from itertools import chain +from typing import Optional + +import datasets +import evaluate +import torch +from datasets import load_dataset + +import transformers +from transformers import ( + CONFIG_MAPPING, + MODEL_FOR_CAUSAL_LM_MAPPING, + AutoConfig, + AutoModelForCausalLM, + AutoTokenizer, + HfArgumentParser, + Trainer, + TrainingArguments, + default_data_collator, + is_torch_tpu_available, + set_seed, +) +from transformers.testing_utils import CaptureLogger +from transformers.trainer_utils import get_last_checkpoint +from transformers.utils import check_min_version, send_example_telemetry +from transformers.utils.versions import require_version + + +# Will error if the minimal version of Transformers is not installed. Remove at your own risks. +# check_min_version("4.29.0.dev0") + +require_version( + "datasets>=1.8.0", + "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt", +) + +logger = logging.getLogger(__name__) + + +MODEL_CONFIG_CLASSES = list(MODEL_FOR_CAUSAL_LM_MAPPING.keys()) +MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) + + +@dataclass +class ModelArguments: + """ + Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch. + """ + + model_name_or_path: Optional[str] = field( + default=None, + metadata={ + "help": ( + "The model checkpoint for weights initialization.Don't set if you want to train a model from scratch." + ) + }, + ) + model_type: Optional[str] = field( + default=None, + metadata={ + "help": "If training from scratch, pass a model type from the list: " + + ", ".join(MODEL_TYPES) + }, + ) + config_overrides: Optional[str] = field( + default=None, + metadata={ + "help": ( + "Override some existing default config settings when a model is trained from scratch. Example: " + "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index" + ) + }, + ) + config_name: Optional[str] = field( + default=None, + metadata={ + "help": "Pretrained config name or path if not the same as model_name" + }, + ) + tokenizer_name: Optional[str] = field( + default=None, + metadata={ + "help": "Pretrained tokenizer name or path if not the same as model_name" + }, + ) + cache_dir: Optional[str] = field( + default=None, + metadata={ + "help": "Where do you want to store the pretrained models downloaded from huggingface.co" + }, + ) + use_fast_tokenizer: bool = field( + default=True, + metadata={ + "help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not." + }, + ) + model_revision: str = field( + default="main", + metadata={ + "help": "The specific model version to use (can be a branch name, tag name or commit id)." + }, + ) + use_auth_token: bool = field( + default=False, + metadata={ + "help": ( + "Will use the token generated when running `huggingface-cli login` (necessary to use this script " + "with private models)." + ) + }, + ) + torch_dtype: Optional[str] = field( + default=None, + metadata={ + "help": ( + "Override the default `torch.dtype` and load the model under this dtype. If `auto` is passed, the " + "dtype will be automatically derived from the model's weights." + ), + "choices": ["auto", "bfloat16", "float16", "float32"], + }, + ) + low_cpu_mem_usage: bool = field( + default=False, + metadata={ + "help": ( + "It is an option to create the model as an empty shell, then only materialize its parameters when the pretrained weights are loaded." + "set True will benefit LLM loading time and RAM consumption." + ) + }, + ) + + def __post_init__(self): + if self.config_overrides is not None and ( + self.config_name is not None or self.model_name_or_path is not None + ): + raise ValueError( + "--config_overrides can't be used in combination with --config_name or --model_name_or_path" + ) + + +@dataclass +class DataTrainingArguments: + """ + Arguments pertaining to what data we are going to input our model for training and eval. + """ + + dataset_name: Optional[str] = field( + default=None, + metadata={"help": "The name of the dataset to use (via the datasets library)."}, + ) + dataset_config_name: Optional[str] = field( + default=None, + metadata={ + "help": "The configuration name of the dataset to use (via the datasets library)." + }, + ) + train_file: Optional[str] = field( + default=None, metadata={"help": "The input training data file (a text file)."} + ) + validation_file: Optional[str] = field( + default=None, + metadata={ + "help": "An optional input evaluation data file to evaluate the perplexity on (a text file)." + }, + ) + max_train_samples: Optional[int] = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of training examples to this " + "value if set." + ) + }, + ) + max_eval_samples: Optional[int] = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of evaluation examples to this " + "value if set." + ) + }, + ) + streaming: bool = field(default=False, metadata={"help": "Enable streaming mode"}) + block_size: Optional[int] = field( + default=None, + metadata={ + "help": ( + "Optional input sequence length after tokenization. " + "The training dataset will be truncated in block of this size for training. " + "Default to the model max input length for single sentence inputs (take into account special tokens)." + ) + }, + ) + overwrite_cache: bool = field( + default=False, + metadata={"help": "Overwrite the cached training and evaluation sets"}, + ) + validation_split_percentage: Optional[int] = field( + default=5, + metadata={ + "help": "The percentage of the train set used as validation set in case there's no validation split" + }, + ) + preprocessing_num_workers: Optional[int] = field( + default=None, + metadata={"help": "The number of processes to use for the preprocessing."}, + ) + keep_linebreaks: bool = field( + default=True, + metadata={"help": "Whether to keep line breaks when using TXT files or not."}, + ) + + def __post_init__(self): + if self.streaming: + require_version( + "datasets>=2.0.0", "The streaming feature requires `datasets>=2.0.0`" + ) + + if ( + self.dataset_name is None + and self.train_file is None + and self.validation_file is None + ): + raise ValueError( + "Need either a dataset name or a training/validation file." + ) + else: + if self.train_file is not None: + extension = self.train_file.split(".")[-1] + assert extension in [ + "csv", + "json", + "txt", + ], "`train_file` should be a csv, a json or a txt file." + if self.validation_file is not None: + extension = self.validation_file.split(".")[-1] + assert extension in [ + "csv", + "json", + "txt", + ], "`validation_file` should be a csv, a json or a txt file." + + +def main(): + # See all possible arguments in src/transformers/training_args.py + # or by passing the --help flag to this script. + # We now keep distinct sets of args, for a cleaner separation of concerns. + + parser = HfArgumentParser( + (ModelArguments, DataTrainingArguments, TrainingArguments) + ) + if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): + # If we pass only one argument to the script and it's the path to a json file, + # let's parse it to get our arguments. + model_args, data_args, training_args = parser.parse_json_file( + json_file=os.path.abspath(sys.argv[1]) + ) + else: + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + + # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The + # information sent is the one passed as arguments along with your Python/PyTorch versions. + send_example_telemetry("run_clm", model_args, data_args) + + # Setup logging + logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", + datefmt="%m/%d/%Y %H:%M:%S", + handlers=[logging.StreamHandler(sys.stdout)], + ) + + if training_args.should_log: + # The default of training_args.log_level is passive, so we set log level at info here to have that default. + transformers.utils.logging.set_verbosity_info() + + log_level = training_args.get_process_log_level() + logger.setLevel(log_level) + datasets.utils.logging.set_verbosity(log_level) + transformers.utils.logging.set_verbosity(log_level) + transformers.utils.logging.enable_default_handler() + transformers.utils.logging.enable_explicit_format() + + # Log on each process the small summary: + logger.warning( + f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" + ) + logger.info(f"Training/evaluation parameters {training_args}") + + # Detecting last checkpoint. + last_checkpoint = None + if ( + os.path.isdir(training_args.output_dir) + and training_args.do_train + and not training_args.overwrite_output_dir + ): + last_checkpoint = get_last_checkpoint(training_args.output_dir) + if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: + raise ValueError( + f"Output directory ({training_args.output_dir}) already exists and is not empty. " + "Use --overwrite_output_dir to overcome." + ) + elif ( + last_checkpoint is not None and training_args.resume_from_checkpoint is None + ): + logger.info( + f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " + "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." + ) + + # Set seed before initializing model. + set_seed(training_args.seed) + + # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) + # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ + # (the dataset will be downloaded automatically from the datasets Hub). + # + # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called + # 'text' is found. You can easily tweak this behavior (see below). + # + # In distributed training, the load_dataset function guarantee that only one local process can concurrently + # download the dataset. + if data_args.dataset_name is not None: + # Downloading and loading a dataset from the hub. + raw_datasets = load_dataset( + data_args.dataset_name, + data_args.dataset_config_name, + cache_dir=model_args.cache_dir, + use_auth_token=True if model_args.use_auth_token else None, + streaming=data_args.streaming, + ) + if "validation" not in raw_datasets.keys(): + raw_datasets["validation"] = load_dataset( + data_args.dataset_name, + data_args.dataset_config_name, + split=f"train[:{data_args.validation_split_percentage}%]", + cache_dir=model_args.cache_dir, + use_auth_token=True if model_args.use_auth_token else None, + streaming=data_args.streaming, + ) + raw_datasets["train"] = load_dataset( + data_args.dataset_name, + data_args.dataset_config_name, + split=f"train[{data_args.validation_split_percentage}%:]", + cache_dir=model_args.cache_dir, + use_auth_token=True if model_args.use_auth_token else None, + streaming=data_args.streaming, + ) + else: + data_files = {} + dataset_args = {} + if data_args.train_file is not None: + data_files["train"] = data_args.train_file + if data_args.validation_file is not None: + data_files["validation"] = data_args.validation_file + extension = ( + data_args.train_file.split(".")[-1] + if data_args.train_file is not None + else data_args.validation_file.split(".")[-1] + ) + if extension == "txt": + extension = "text" + dataset_args["keep_linebreaks"] = data_args.keep_linebreaks + raw_datasets = load_dataset( + extension, + data_files=data_files, + cache_dir=model_args.cache_dir, + use_auth_token=True if model_args.use_auth_token else None, + **dataset_args, + ) + # If no validation data is there, validation_split_percentage will be used to divide the dataset. + if "validation" not in raw_datasets.keys(): + raw_datasets["validation"] = load_dataset( + extension, + data_files=data_files, + split=f"train[:{data_args.validation_split_percentage}%]", + cache_dir=model_args.cache_dir, + use_auth_token=True if model_args.use_auth_token else None, + **dataset_args, + ) + raw_datasets["train"] = load_dataset( + extension, + data_files=data_files, + split=f"train[{data_args.validation_split_percentage}%:]", + cache_dir=model_args.cache_dir, + use_auth_token=True if model_args.use_auth_token else None, + **dataset_args, + ) + + # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at + # https://huggingface.co/docs/datasets/loading_datasets.html. + + # Load pretrained model and tokenizer + # + # Distributed training: + # The .from_pretrained methods guarantee that only one local process can concurrently + # download model & vocab. + + config_kwargs = { + "cache_dir": model_args.cache_dir, + "revision": model_args.model_revision, + "use_auth_token": True if model_args.use_auth_token else None, + } + if model_args.config_name: + config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs) + elif model_args.model_name_or_path: + config = AutoConfig.from_pretrained( + model_args.model_name_or_path, **config_kwargs + ) + else: + config = CONFIG_MAPPING[model_args.model_type]() + logger.warning("You are instantiating a new config instance from scratch.") + if model_args.config_overrides is not None: + logger.info(f"Overriding config: {model_args.config_overrides}") + config.update_from_string(model_args.config_overrides) + logger.info(f"New config: {config}") + + tokenizer_kwargs = { + "cache_dir": model_args.cache_dir, + "use_fast": model_args.use_fast_tokenizer, + "revision": model_args.model_revision, + "use_auth_token": True if model_args.use_auth_token else None, + } + if model_args.tokenizer_name: + tokenizer = AutoTokenizer.from_pretrained( + model_args.tokenizer_name, **tokenizer_kwargs + ) + elif model_args.model_name_or_path: + tokenizer = AutoTokenizer.from_pretrained( + model_args.model_name_or_path, **tokenizer_kwargs + ) + else: + raise ValueError( + "You are instantiating a new tokenizer from scratch. This is not supported by this script." + "You can do it from another script, save it, and load it from here, using --tokenizer_name." + ) + + if model_args.model_name_or_path: + torch_dtype = ( + model_args.torch_dtype + if model_args.torch_dtype in ["auto", None] + else getattr(torch, model_args.torch_dtype) + ) + model = AutoModelForCausalLM.from_pretrained( + model_args.model_name_or_path, + from_tf=bool(".ckpt" in model_args.model_name_or_path), + config=config, + cache_dir=model_args.cache_dir, + revision=model_args.model_revision, + use_auth_token=True if model_args.use_auth_token else None, + torch_dtype=torch_dtype, + low_cpu_mem_usage=model_args.low_cpu_mem_usage, + ) + else: + model = AutoModelForCausalLM.from_config(config) + n_params = sum({p.data_ptr(): p.numel() for p in model.parameters()}.values()) + logger.info( + f"Training new model from scratch - Total size={n_params/2**20:.2f}M params" + ) + + # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch + # on a small vocab and want a smaller embedding size, remove this test. + embedding_size = model.get_input_embeddings().weight.shape[0] + if len(tokenizer) > embedding_size: + model.resize_token_embeddings(len(tokenizer)) + + # Preprocessing the datasets. + # First we tokenize all the texts. + if training_args.do_train: + column_names = list(raw_datasets["train"].features) + else: + column_names = list(raw_datasets["validation"].features) + text_column_name = "text" if "text" in column_names else column_names[0] + + # since this will be pickled to avoid _LazyModule error in Hasher force logger loading before tokenize_function + tok_logger = transformers.utils.logging.get_logger( + "transformers.tokenization_utils_base" + ) + + def tokenize_function(examples): + with CaptureLogger(tok_logger) as cl: + output = tokenizer(examples[text_column_name]) + # clm input could be much much longer than block_size + if "Token indices sequence length is longer than the" in cl.out: + tok_logger.warning( + "^^^^^^^^^^^^^^^^ Please ignore the warning above - this long input will be chunked into smaller bits" + " before being passed to the model." + ) + return output + + with training_args.main_process_first(desc="dataset map tokenization"): + if not data_args.streaming: + tokenized_datasets = raw_datasets.map( + tokenize_function, + batched=True, + num_proc=data_args.preprocessing_num_workers, + remove_columns=column_names, + load_from_cache_file=not data_args.overwrite_cache, + desc="Running tokenizer on dataset", + ) + else: + tokenized_datasets = raw_datasets.map( + tokenize_function, + batched=True, + remove_columns=column_names, + ) + + if data_args.block_size is None: + block_size = tokenizer.model_max_length + if block_size > 1024: + logger.warning( + "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" + " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" + " override this default with `--block_size xxx`." + ) + block_size = 1024 + else: + if data_args.block_size > tokenizer.model_max_length: + logger.warning( + f"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model" + f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}." + ) + block_size = min(data_args.block_size, tokenizer.model_max_length) + + # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size. + def group_texts(examples): + # Concatenate all texts. + concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()} + total_length = len(concatenated_examples[list(examples.keys())[0]]) + # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can + # customize this part to your needs. + if total_length >= block_size: + total_length = (total_length // block_size) * block_size + # Split by chunks of max_len. + result = { + k: [t[i : i + block_size] for i in range(0, total_length, block_size)] + for k, t in concatenated_examples.items() + } + result["labels"] = result["input_ids"].copy() + return result + + # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder + # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower + # to preprocess. + # + # To speed up this part, we use multiprocessing. See the documentation of the map method for more information: + # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map + + with training_args.main_process_first(desc="grouping texts together"): + if not data_args.streaming: + lm_datasets = tokenized_datasets.map( + group_texts, + batched=True, + num_proc=data_args.preprocessing_num_workers, + load_from_cache_file=not data_args.overwrite_cache, + desc=f"Grouping texts in chunks of {block_size}", + ) + else: + lm_datasets = tokenized_datasets.map( + group_texts, + batched=True, + ) + + if training_args.do_train: + if "train" not in tokenized_datasets: + raise ValueError("--do_train requires a train dataset") + train_dataset = lm_datasets["train"] + if data_args.max_train_samples is not None: + max_train_samples = min(len(train_dataset), data_args.max_train_samples) + train_dataset = train_dataset.select(range(max_train_samples)) + + if training_args.do_eval: + if "validation" not in tokenized_datasets: + raise ValueError("--do_eval requires a validation dataset") + eval_dataset = lm_datasets["validation"] + if data_args.max_eval_samples is not None: + max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples) + eval_dataset = eval_dataset.select(range(max_eval_samples)) + + def preprocess_logits_for_metrics(logits, labels): + if isinstance(logits, tuple): + # Depending on the model and config, logits may contain extra tensors, + # like past_key_values, but logits always come first + logits = logits[0] + return logits.argmax(dim=-1) + + metric = evaluate.load("accuracy") + + def compute_metrics(eval_preds): + preds, labels = eval_preds + # preds have the same shape as the labels, after the argmax(-1) has been calculated + # by preprocess_logits_for_metrics but we need to shift the labels + labels = labels[:, 1:].reshape(-1) + preds = preds[:, :-1].reshape(-1) + return metric.compute(predictions=preds, references=labels) + + # Initialize our Trainer + trainer = Trainer( + model=model, + args=training_args, + train_dataset=train_dataset if training_args.do_train else None, + eval_dataset=eval_dataset if training_args.do_eval else None, + tokenizer=tokenizer, + # Data collator will default to DataCollatorWithPadding, so we change it. + data_collator=default_data_collator, + compute_metrics=compute_metrics + if training_args.do_eval and not is_torch_tpu_available() + else None, + preprocess_logits_for_metrics=preprocess_logits_for_metrics + if training_args.do_eval and not is_torch_tpu_available() + else None, + ) + + # Training + if training_args.do_train: + checkpoint = None + if training_args.resume_from_checkpoint is not None: + checkpoint = training_args.resume_from_checkpoint + elif last_checkpoint is not None: + checkpoint = last_checkpoint + train_result = trainer.train(resume_from_checkpoint=checkpoint) + trainer.save_model() # Saves the tokenizer too for easy upload + + metrics = train_result.metrics + + max_train_samples = ( + data_args.max_train_samples + if data_args.max_train_samples is not None + else len(train_dataset) + ) + metrics["train_samples"] = min(max_train_samples, len(train_dataset)) + + trainer.log_metrics("train", metrics) + trainer.save_metrics("train", metrics) + trainer.save_state() + + # Evaluation + if training_args.do_eval: + logger.info("*** Evaluate ***") + + metrics = trainer.evaluate() + + max_eval_samples = ( + data_args.max_eval_samples + if data_args.max_eval_samples is not None + else len(eval_dataset) + ) + metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) + try: + perplexity = math.exp(metrics["eval_loss"]) + except OverflowError: + perplexity = float("inf") + metrics["perplexity"] = perplexity + + trainer.log_metrics("eval", metrics) + trainer.save_metrics("eval", metrics) + + kwargs = { + "finetuned_from": model_args.model_name_or_path, + "tasks": "text-generation", + } + if data_args.dataset_name is not None: + kwargs["dataset_tags"] = data_args.dataset_name + if data_args.dataset_config_name is not None: + kwargs["dataset_args"] = data_args.dataset_config_name + kwargs[ + "dataset" + ] = f"{data_args.dataset_name} {data_args.dataset_config_name}" + else: + kwargs["dataset"] = data_args.dataset_name + + if training_args.push_to_hub: + trainer.push_to_hub(**kwargs) + else: + trainer.create_model_card(**kwargs) + + +def _mp_fn(index): + # For xla_spawn (TPUs) + main() + + +if __name__ == "__main__": + main() diff --git a/demo-notebooks/guided-demos/preview_nbs/mnist.py b/demo-notebooks/guided-demos/preview_nbs/mnist.py new file mode 100644 index 000000000..6eb663dc7 --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/mnist.py @@ -0,0 +1,160 @@ +# Copyright 2022 IBM, Red Hat +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# In[] +import os + +import torch +from pytorch_lightning import LightningModule, Trainer +from pytorch_lightning.callbacks.progress import TQDMProgressBar +from pytorch_lightning.loggers import CSVLogger +from torch import nn +from torch.nn import functional as F +from torch.utils.data import DataLoader, random_split +from torchmetrics import Accuracy +from torchvision import transforms +from torchvision.datasets import MNIST + +PATH_DATASETS = os.environ.get("PATH_DATASETS", ".") +BATCH_SIZE = 256 if torch.cuda.is_available() else 64 +# %% + +print("prior to running the trainer") +print("MASTER_ADDR: is ", os.getenv("MASTER_ADDR")) +print("MASTER_PORT: is ", os.getenv("MASTER_PORT")) + + +class LitMNIST(LightningModule): + def __init__(self, data_dir=PATH_DATASETS, hidden_size=64, learning_rate=2e-4): + super().__init__() + + # Set our init args as class attributes + self.data_dir = data_dir + self.hidden_size = hidden_size + self.learning_rate = learning_rate + + # Hardcode some dataset specific attributes + self.num_classes = 10 + self.dims = (1, 28, 28) + channels, width, height = self.dims + self.transform = transforms.Compose( + [ + transforms.ToTensor(), + transforms.Normalize((0.1307,), (0.3081,)), + ] + ) + + # Define PyTorch model + self.model = nn.Sequential( + nn.Flatten(), + nn.Linear(channels * width * height, hidden_size), + nn.ReLU(), + nn.Dropout(0.1), + nn.Linear(hidden_size, hidden_size), + nn.ReLU(), + nn.Dropout(0.1), + nn.Linear(hidden_size, self.num_classes), + ) + + self.val_accuracy = Accuracy() + self.test_accuracy = Accuracy() + + def forward(self, x): + x = self.model(x) + return F.log_softmax(x, dim=1) + + def training_step(self, batch, batch_idx): + x, y = batch + logits = self(x) + loss = F.nll_loss(logits, y) + return loss + + def validation_step(self, batch, batch_idx): + x, y = batch + logits = self(x) + loss = F.nll_loss(logits, y) + preds = torch.argmax(logits, dim=1) + self.val_accuracy.update(preds, y) + + # Calling self.log will surface up scalars for you in TensorBoard + self.log("val_loss", loss, prog_bar=True) + self.log("val_acc", self.val_accuracy, prog_bar=True) + + def test_step(self, batch, batch_idx): + x, y = batch + logits = self(x) + loss = F.nll_loss(logits, y) + preds = torch.argmax(logits, dim=1) + self.test_accuracy.update(preds, y) + + # Calling self.log will surface up scalars for you in TensorBoard + self.log("test_loss", loss, prog_bar=True) + self.log("test_acc", self.test_accuracy, prog_bar=True) + + def configure_optimizers(self): + optimizer = torch.optim.Adam(self.parameters(), lr=self.learning_rate) + return optimizer + + #################### + # DATA RELATED HOOKS + #################### + + def prepare_data(self): + # download + print("Downloading MNIST dataset...") + MNIST(self.data_dir, train=True, download=True) + MNIST(self.data_dir, train=False, download=True) + + def setup(self, stage=None): + # Assign train/val datasets for use in dataloaders + if stage == "fit" or stage is None: + mnist_full = MNIST(self.data_dir, train=True, transform=self.transform) + self.mnist_train, self.mnist_val = random_split(mnist_full, [55000, 5000]) + + # Assign test dataset for use in dataloader(s) + if stage == "test" or stage is None: + self.mnist_test = MNIST( + self.data_dir, train=False, transform=self.transform + ) + + def train_dataloader(self): + return DataLoader(self.mnist_train, batch_size=BATCH_SIZE) + + def val_dataloader(self): + return DataLoader(self.mnist_val, batch_size=BATCH_SIZE) + + def test_dataloader(self): + return DataLoader(self.mnist_test, batch_size=BATCH_SIZE) + + +# Init DataLoader from MNIST Dataset + +model = LitMNIST() + +print("GROUP: ", int(os.environ.get("GROUP_WORLD_SIZE", 1))) +print("LOCAL: ", int(os.environ.get("LOCAL_WORLD_SIZE", 1))) + +# Initialize a trainer +trainer = Trainer( + accelerator="auto", + # devices=1 if torch.cuda.is_available() else None, # limiting got iPython runs + max_epochs=5, + callbacks=[TQDMProgressBar(refresh_rate=20)], + num_nodes=int(os.environ.get("GROUP_WORLD_SIZE", 1)), + devices=int(os.environ.get("LOCAL_WORLD_SIZE", 1)), + strategy="ddp", +) + +# Train the model โšก +trainer.fit(model) diff --git a/demo-notebooks/guided-demos/preview_nbs/requirements.txt b/demo-notebooks/guided-demos/preview_nbs/requirements.txt new file mode 100644 index 000000000..7266b064a --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/requirements.txt @@ -0,0 +1,4 @@ +pytorch_lightning==1.5.10 +ray_lightning +torchmetrics==0.9.1 +torchvision==0.12.0 diff --git a/demo-notebooks/guided-demos/preview_nbs/requirements_gpt.txt b/demo-notebooks/guided-demos/preview_nbs/requirements_gpt.txt new file mode 100644 index 000000000..bd6c4f525 --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/requirements_gpt.txt @@ -0,0 +1,8 @@ +accelerate >= 0.12.0 +torch >= 1.3 +datasets >= 1.8.0 +sentencepiece != 0.1.92 +evaluate +scikit-learn +transformers==4.28.1 +protobuf<=3.20.1,>=3.8.0