diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 00000000..a894e29e
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+*.ipynb linguist-detectable=false
diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml
index 57070739..db952e8e 100644
--- a/.github/workflows/release.yaml
+++ b/.github/workflows/release.yaml
@@ -47,7 +47,7 @@ jobs:
- name: Run poetry build
run: poetry build
- name: Create new documentation
- run: poetry run pdoc --html -o docs src/codeflare_sdk && pushd docs && rm -rf cluster job utils && mv codeflare_sdk/* . && rm -rf codeflare_sdk && popd
+ run: poetry run pdoc --html -o docs src/codeflare_sdk && pushd docs && rm -rf cluster job utils && mv codeflare_sdk/* . && rm -rf codeflare_sdk && popd && find docs -type f -name "*.html" -exec bash -c "echo '' >> {}" \;
- name: Set Pypi token
run: poetry config pypi-token.pypi ${{ secrets.PYPI_TOKEN }}
- name: Publish new release to Pypi repository
diff --git a/.gitignore b/.gitignore
index e4af971d..fbb31b2b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,3 +5,7 @@ __pycache__/
Pipfile
Pipfile.lock
poetry.lock
+.venv*
+build/
+tls-cluster-namespace
+quicktest.yaml
diff --git a/CodeFlareSDK_Design_Doc.md b/CodeFlareSDK_Design_Doc.md
new file mode 100644
index 00000000..0274f65d
--- /dev/null
+++ b/CodeFlareSDK_Design_Doc.md
@@ -0,0 +1,113 @@
+# CodeFlare SDK Design Doc
+
+## Context and Scope
+
+The primary purpose for the CodeFlare SDK is to provide a pythonic interaction layer between a user and the CodeFlare Stack (a set of services that enable advanced queuing, resource management and distributed compute on Kubernetes).
+
+The reason that this SDK is needed is due to the fact that many of the benefits associated with the CodeFlare stack are aimed at making the work of data scientists simpler and more efficient. However, since all parts of the CodeFlare stack are separate Kubernetes services, there needs to be something that unifies the interactions between the user and these separate services. Furthermore, we do not expect the average user to be experienced working with Kubernetes infrastructure, and want to provide them with a Python native way of interacting with these services.
+
+The SDK should support any operation that a user would need to do in order to successfully submit machine learning training jobs to their kubernetes cluster.
+
+## Goals
+
+* Serve as an interaction layer between a data scientist and the CodeFlare Stack (MCAD, InstaScale, KubeRay)
+* Abstract away user’s infrastructure concerns; Specifically, dealing with Kubernetes resources, consoles, or CLI’s (kubectl).
+* Provide users the ability to programmatically request, monitor, and stop the kubernetes resources associated with the CodeFlare stack.
+
+## Non-Goals
+
+* We do not want to re-implement any existing SDK’s or clients for Ray, MCAD, or any other service.
+
+## Architecture and Design
+
+The CodeFlare SDK is a python package that allows a user to programmatically define, create, monitor, and shutdown framework clusters (RayClusters for now) as well as define, submit, monitor and cancel distributed training jobs for machine learning models on an authenticated Kubernetes cluster that has the CodeFlare Stack installed.
+
+In order to achieve this we need the capacity to:
+
+* Generate valid AppWrapper yaml files based on user provided parameters
+* Get, list, watch, create, update, patch, and delete AppWrapper custom resources on a kubernetes cluster
+* Get, list, watch, create, update, patch, and delete RayCluster custom resources on a kubernetes cluster.
+* Expose a secure route to the Ray Dashboard endpoint.
+* Define, submit, monitor and cancel Jobs submitted via TorchX. TorchX jobs must support both Ray and MCAD-Kubernetes scheduler backends.
+* Provide means of authenticating to a Kubernetes cluster
+
+
+
+### Framework Clusters:
+
+In order to create these framework clusters, we will start with a [template AppWrapper yaml file](/src/codeflare_sdk/templates/base-template.yaml) with reasonable defaults that will generate a valid RayCluster via MCAD.
+
+Users can customize their AppWrapper by passing their desired parameters to `ClusterConfig()` and applying that configuration when initializing a `Cluster()` object. When a `Cluster()` is initialized, it will update the AppWrapper template with the user’s specified requirements, and save it to the current working directory.
+
+Our aim is to simplify the process of generating valid AppWrappers for RayClusters, so we will strive to find the appropriate balance between ease of use and exposing all possible AppWrapper parameters. And we will find this balance through user feedback.
+
+With a valid AppWrapper, we will use the Kubernetes python client to apply the AppWrapper to our Kubernetes cluster via a call to `cluster.up()`
+
+We will also use the Kubernetes python client to get information about both the RayCluster and AppWrapper custom resources to monitor the status of our Framework Cluster via `cluster.status()` and `cluster.details()`.
+
+The RayCluster deployed on your Kubernetes cluster can be interacted with in two ways: Either through an interactive session via `ray.init()` or through the submission of batch jobs.
+
+Finally we will use the Kubernetes python client to delete the AppWrapper via `cluster.down()`
+
+### Training Jobs:
+
+For the submission of Jobs we will rely on the [TorchX](https://pytorch.org/torchx/latest/) job launcher to handle orchestrating the distribution of our model training jobs across the available resources on our cluster. We will support two distributed backend schedulers: Ray and Kubernetes-MCAD. TorchX is designed to be used primarily as a CLI, so we will wrap a limited subset of its functionality into our SDK so that it can be used as part of a python script.
+
+Users can define their jobs with `DDPJobDefinition()` providing parameters for the script they want to run as part of the job, the resources required for the job, additional args specific to the script being run and scheduler being used.
+
+Once a job is defined it can be submitted to the Kubernetes cluster to be run via `job.submit()`. If `job.submit()` is left empty the SDK will assume the Kubernetes-MCAD scheduler is being used. If a RayCluster is specified like, `job.submit(cluster)`, then the SDK will assume that the Ray scheduler is being used and submit the job to that RayCluster.
+
+After the job is submitted, a user can monitor its progress via `job.status()` and `job.logs()` to retrieve the status and logs output by the job. At any point the user can also call `job.cancel()` to stop the job.
+
+### Authentication:
+
+Since we are dealing with controlling and accessing different resources on a Kubernetes cluster, the user will need to have certain permissions on that cluster granted to them by their cluster administrator.
+
+The SDK itself will not enforce any authentication, however, it will provide simple interfaces to allow users to authenticate themselves to their Kubernetes cluster. By default, if a user is already authenticated with a `~/.kube/config` file, that authentication will automatically be picked up by the SDK and no additional authentication is required.
+
+Users can authorize themselves by calling `TokenAuthentication()` and providing their access token and server address. This will populate the Kubernetes python configuration of the ApiClient object and allow users to be properly authenticated to the cluster. Users are also able to toggle whether or not they want to skip tls verification.
+
+Alternatively users can provide their own custom kubeconfig file with `KubeConfigFileAuthentication()` and pass it the correct path.
+
+In either case, users can log out and clear the authentication inputs with `.logout()`
+
+## Alternatives Considered
+
+* Ray API Server
+ * Has no notion of MCAD. Does not support any other backends beside Ray. (However, this may change in the near future)
+* Ray Python Client
+ * Has no notion of MCAD. Does not support any other backends besides Ray
+* Existing CodeFlare CLI
+ * Is not pythonic.
+* Nothing (let users define their own AppWrappers manually)
+ * Antithetical to the purpose of the SDK.
+
+## Security Considerations
+
+
+We will rely on the Kubernetes cluster’s default security, where users cannot perform any operations on a cluster if they are not authenticated correctly.
+
+## Testing and Validation
+
+* Testing plan and strategies
+
+ * Unit testing for all SDK functionality
+ * Integration testing of SDK interactions with OpenShift and Kubernetes
+ * System tests of SDK as part of the entire CodeFlare stack for main scenarios
+* Unit testing, integration testing, and system testing approaches
+ * Unit testing will occur with every PR.
+ * For system testing we can leverage [current e2e](https://github.com/project-codeflare/codeflare-operator/tree/main/test/e2e) tests from the operator repo.
+* Validation criteria and expected outcomes
+ * Minimum of 95% code coverage at all times.
+ * Expect all unit tests to pass before a PR is merged.
+ * Expect all integration and system tests to pass before a new release.
+
+## Deployment and Rollout
+
+* Deployment strategy and considerations
+ * The SDK is part of the wider project CodeFlare ecosystem, and serves as the primary interaction layer between the user and the rest of the CodeFlare stack. Therefore, deployment and release strategies cannot occur in isolation, but must take into consideration the current state of the other pieces of the CodeFlare stack (MCAD, KubeRay, Instascale)
+
+* Versioning and release management
+ * Releases are performed automatically via a github action.
+ * The SDK can have minor releases for urgent bug fixes.
+ * The SDK will normally have a new release alongside the rest of the CodeFlare stack with the same version number.
diff --git a/assets/images/sdk-diagram.png b/assets/images/sdk-diagram.png
new file mode 100644
index 00000000..adf2a7e1
Binary files /dev/null and b/assets/images/sdk-diagram.png differ
diff --git a/coverage.svg b/coverage.svg
index ee07d4c2..c1490035 100644
--- a/coverage.svg
+++ b/coverage.svg
@@ -9,13 +9,13 @@
-
+
coverage
coverage
- 96%
- 96%
+ 90%
+ 90%
diff --git a/custom-nb-image/imagestream.yaml b/custom-nb-image/imagestream.yaml
index e44c2f09..bd17076f 100644
--- a/custom-nb-image/imagestream.yaml
+++ b/custom-nb-image/imagestream.yaml
@@ -21,7 +21,7 @@ metadata:
annotations:
opendatahub.io/notebook-image-name:
"CodeFlare Notebook"
- opendatahub.io/notebook-image-desc: "Custom Jupyter notebook image with CodeFlare SDK, Python 3.8, Ray 2.1.0 and PyTorch 1.12.1"
+ opendatahub.io/notebook-image-desc: "Custom Jupyter notebook image with CodeFlare SDK, Python 3.8, Ray 2.5.0 and PyTorch 1.12.1"
spec:
lookupPolicy:
local: true
diff --git a/custom-nb-image/requirements.txt b/custom-nb-image/requirements.txt
index 17822fab..35b5d559 100644
--- a/custom-nb-image/requirements.txt
+++ b/custom-nb-image/requirements.txt
@@ -157,7 +157,7 @@ python-json-logger==2.0.4; python_version >= '3.5'
pytz==2022.2.1
pyyaml==6.0; python_version >= '3.6'
pyzmq==24.0.1; python_version >= '3.6'
-ray[default]==2.1.0
+ray[default]==2.5.0
requests-oauthlib==1.3.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
requests==2.28.1; python_version >= '3.7' and python_version < '4'
rsa==4.9; python_version >= '3.6'
diff --git a/demo-notebooks/batch-job/batch_mnist_ray.ipynb b/demo-notebooks/batch-job/batch_mnist_ray.ipynb
index 88b05070..b725bfc5 100644
--- a/demo-notebooks/batch-job/batch_mnist_ray.ipynb
+++ b/demo-notebooks/batch-job/batch_mnist_ray.ipynb
@@ -63,6 +63,7 @@
" min_memory=16,\n",
" max_memory=16,\n",
" gpu=4,\n",
+ " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\",\n",
" instascale=True, # Can be set to false if scaling not needed\n",
" machine_types=[\"m5.xlarge\", \"g4dn.xlarge\"] # Can be removed if above is false\n",
"))"
@@ -88,7 +89,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "657ebdfb",
"metadata": {},
@@ -222,7 +222,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "b3a55fe4",
"metadata": {},
@@ -5224,7 +5223,7 @@
],
"metadata": {
"kernelspec": {
- "display_name": "sdktest",
+ "display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
diff --git a/demo-notebooks/guided-demos/0_basic_ray.ipynb b/demo-notebooks/guided-demos/0_basic_ray.ipynb
index 7daf4b88..338f5730 100644
--- a/demo-notebooks/guided-demos/0_basic_ray.ipynb
+++ b/demo-notebooks/guided-demos/0_basic_ray.ipynb
@@ -1,7 +1,6 @@
{
"cells": [
{
- "attachments": {},
"cell_type": "markdown",
"id": "8d4a42f6",
"metadata": {},
@@ -65,6 +64,7 @@
" max_cpus=1,\n",
" min_memory=4,\n",
" max_memory=4,\n",
+ " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\",\n",
" gpu=0,\n",
" instascale=False\n",
"))"
@@ -90,7 +90,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "657ebdfb",
"metadata": {},
@@ -129,7 +128,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "b3a55fe4",
"metadata": {},
@@ -178,7 +176,7 @@
],
"metadata": {
"kernelspec": {
- "display_name": "Python 3",
+ "display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
@@ -192,7 +190,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.9.13"
+ "version": "3.8.13"
},
"vscode": {
"interpreter": {
diff --git a/demo-notebooks/guided-demos/1_basic_instascale.ipynb b/demo-notebooks/guided-demos/1_basic_instascale.ipynb
index 8bb86e12..cc5c8224 100644
--- a/demo-notebooks/guided-demos/1_basic_instascale.ipynb
+++ b/demo-notebooks/guided-demos/1_basic_instascale.ipynb
@@ -1,7 +1,6 @@
{
"cells": [
{
- "attachments": {},
"cell_type": "markdown",
"id": "9865ee8c",
"metadata": {},
@@ -38,7 +37,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "bc27f84c",
"metadata": {},
@@ -64,13 +62,13 @@
" min_memory=8,\n",
" max_memory=8,\n",
" gpu=1,\n",
+ " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\",\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",
"))"
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "12eef53c",
"metadata": {},
@@ -91,7 +89,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "6abfe904",
"metadata": {},
@@ -130,7 +127,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "c883caea",
"metadata": {},
@@ -151,7 +147,7 @@
],
"metadata": {
"kernelspec": {
- "display_name": "Python 3",
+ "display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
@@ -165,7 +161,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.9.13"
+ "version": "3.8.13"
},
"vscode": {
"interpreter": {
diff --git a/demo-notebooks/guided-demos/2_basic_jobs.ipynb b/demo-notebooks/guided-demos/2_basic_jobs.ipynb
index 37560b17..3fe46a8a 100644
--- a/demo-notebooks/guided-demos/2_basic_jobs.ipynb
+++ b/demo-notebooks/guided-demos/2_basic_jobs.ipynb
@@ -1,7 +1,6 @@
{
"cells": [
{
- "attachments": {},
"cell_type": "markdown",
"id": "464af595",
"metadata": {},
@@ -38,7 +37,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "bc27f84c",
"metadata": {},
@@ -64,6 +62,7 @@
" min_memory=4,\n",
" max_memory=4,\n",
" gpu=0,\n",
+ " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\",\n",
" instascale=False\n",
"))"
]
@@ -91,7 +90,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "33663f47",
"metadata": {},
@@ -110,7 +108,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "83d77b74",
"metadata": {},
@@ -134,7 +131,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "5b9ae53a",
"metadata": {},
@@ -163,7 +159,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "5af8cd32",
"metadata": {},
@@ -182,7 +177,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "31096641",
"metadata": {},
@@ -211,7 +205,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "0837e43b",
"metadata": {},
@@ -240,7 +233,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "aebf376a",
"metadata": {},
@@ -271,7 +263,7 @@
],
"metadata": {
"kernelspec": {
- "display_name": "Python 3",
+ "display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
@@ -285,7 +277,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.9.13"
+ "version": "3.8.13"
},
"vscode": {
"interpreter": {
diff --git a/demo-notebooks/guided-demos/3_basic_interactive.ipynb b/demo-notebooks/guided-demos/3_basic_interactive.ipynb
index 4a1b0f6f..9ffed0c7 100644
--- a/demo-notebooks/guided-demos/3_basic_interactive.ipynb
+++ b/demo-notebooks/guided-demos/3_basic_interactive.ipynb
@@ -62,6 +62,7 @@
" min_memory=8,\n",
" max_memory=8,\n",
" gpu=1,\n",
+ " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\",\n",
" instascale=True,\n",
" machine_types=[\"m5.xlarge\", \"g4dn.xlarge\"]\n",
" \n",
@@ -138,7 +139,7 @@
"ray.shutdown()\n",
"# establish connection to ray cluster\n",
"\n",
- "#install additionall libraries that will be required for model training\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",
@@ -275,7 +276,7 @@
],
"metadata": {
"kernelspec": {
- "display_name": "Python 3",
+ "display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
@@ -289,7 +290,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.9.13"
+ "version": "3.8.13"
},
"vscode": {
"interpreter": {
diff --git a/demo-notebooks/guided-demos/4_gpt.ipynb b/demo-notebooks/guided-demos/4_gpt.ipynb
index 0132bd4a..e489c9bc 100644
--- a/demo-notebooks/guided-demos/4_gpt.ipynb
+++ b/demo-notebooks/guided-demos/4_gpt.ipynb
@@ -45,6 +45,7 @@
" min_memory=8,\n",
" max_memory=8,\n",
" gpu=1,\n",
+ " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\",\n",
" instascale=True,\n",
" machine_types=[\"m5.xlarge\", \"g4dn.xlarge\"],\n",
"))"
diff --git a/demo-notebooks/guided-demos/notebook-ex-outputs/3_basic_interactive.ipynb b/demo-notebooks/guided-demos/notebook-ex-outputs/3_basic_interactive.ipynb
index df4c3a94..ebcb52a6 100644
--- a/demo-notebooks/guided-demos/notebook-ex-outputs/3_basic_interactive.ipynb
+++ b/demo-notebooks/guided-demos/notebook-ex-outputs/3_basic_interactive.ipynb
@@ -230,7 +230,7 @@
"ray.shutdown()\n",
"# establish connection to ray cluster\n",
"\n",
- "#install additionall libraries that will be required for model training\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",
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 00000000..b3040676
--- /dev/null
+++ b/demo-notebooks/guided-demos/preview_nbs/0_basic_ray.ipynb
@@ -0,0 +1,202 @@
+{
+ "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",
+ " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\", #current default\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 00000000..8f8a6ed7
--- /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 00000000..eb924715
--- /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 00000000..73eff977
--- /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 00000000..919f8f0a
--- /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/demo-notebooks/guided-demos/preview_nbs/gpt_og.py b/demo-notebooks/guided-demos/preview_nbs/gpt_og.py
new file mode 100644
index 00000000..d69e41fc
--- /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 00000000..6eb663dc
--- /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 00000000..7266b064
--- /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 00000000..bd6c4f52
--- /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
diff --git a/demo-notebooks/interactive/hf_interactive.ipynb b/demo-notebooks/interactive/hf_interactive.ipynb
index ed774821..e80df90d 100644
--- a/demo-notebooks/interactive/hf_interactive.ipynb
+++ b/demo-notebooks/interactive/hf_interactive.ipynb
@@ -86,7 +86,17 @@
],
"source": [
"# Create our cluster and submit appwrapper\n",
- "cluster = Cluster(ClusterConfiguration(name='hfgputest', min_worker=1, max_worker=1, min_cpus=8, max_cpus=8, min_memory=16, max_memory=16, gpu=4, instascale=True, machine_types=[\"m5.xlarge\", \"p3.8xlarge\"]))"
+ "cluster = Cluster(ClusterConfiguration(name='hfgputest', \n",
+ " namespace=\"default\",\n",
+ " min_worker=1, \n",
+ " max_worker=1, \n",
+ " min_cpus=8, \n",
+ " max_cpus=8, \n",
+ " min_memory=16, \n",
+ " max_memory=16, \n",
+ " gpu=4,\n",
+ " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\",\n",
+ " instascale=True, machine_types=[\"m5.xlarge\", \"p3.8xlarge\"]))"
]
},
{
@@ -108,7 +118,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "657ebdfb",
"metadata": {},
@@ -189,7 +198,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "477ac246",
"metadata": {},
@@ -308,8 +316,8 @@
"ray.shutdown()\n",
"# establish connection to ray cluster\n",
"\n",
- "#install additionall libraries that will be required for this training\n",
- "runtime_env = {\"pip\": [\"transformers\", \"datasets\", \"evaluate\"]}\n",
+ "#install additional libraries that will be required for this 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",
@@ -1443,7 +1451,7 @@
],
"metadata": {
"kernelspec": {
- "display_name": "Python 3.9.7 64-bit",
+ "display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
@@ -1457,7 +1465,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.9.13"
+ "version": "3.8.13"
},
"vscode": {
"interpreter": {
diff --git a/demo-notebooks/interactive/local_interactive.ipynb b/demo-notebooks/interactive/local_interactive.ipynb
index 88a6ccd5..d70c00df 100644
--- a/demo-notebooks/interactive/local_interactive.ipynb
+++ b/demo-notebooks/interactive/local_interactive.ipynb
@@ -32,20 +32,12 @@
},
{
"cell_type": "code",
- "execution_count": 2,
+ "execution_count": null,
"id": "4364ac2e-dd10-4d30-ba66-12708daefb3f",
"metadata": {
"tags": []
},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Written to: hfgputest-1.yaml\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"# Create our cluster and submit appwrapper\n",
"namespace = \"default\"\n",
@@ -89,7 +81,6 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"id": "12eef53c",
"metadata": {},
@@ -99,38 +90,21 @@
},
{
"cell_type": "code",
- "execution_count": 11,
+ "execution_count": null,
"id": "cf1b749e-2335-42c2-b673-26768ec9895d",
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "rayclient-hfgputest-1-default.apps.tedbig412.cp.fyre.ibm.com\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
- "import openshift as oc\n",
"from codeflare_sdk.utils import generate_cert\n",
"\n",
"if local_interactive:\n",
" generate_cert.generate_tls_cert(cluster_name, namespace)\n",
- " generate_cert.export_env(cluster_name, namespace)\n",
- "\n",
- "with oc.project(namespace):\n",
- " routes=oc.selector(\"route\").objects()\n",
- " rayclient_url=\"\"\n",
- " for r in routes:\n",
- " if \"rayclient\" in r.name():\n",
- " rayclient_url=r.model.spec.host\n",
- "print(rayclient_url)"
+ " generate_cert.export_env(cluster_name, namespace)"
]
},
{
"cell_type": "code",
- "execution_count": 12,
+ "execution_count": 6,
"id": "9483bb98-33b3-4beb-9b15-163d7e76c1d7",
"metadata": {
"scrolled": true,
@@ -141,15 +115,15 @@
"name": "stderr",
"output_type": "stream",
"text": [
- "2023-05-31 14:12:37,816\tINFO client_builder.py:251 -- Passing the following kwargs to ray.init() on the server: logging_level\n",
- "2023-05-31 14:12:37,820\tDEBUG worker.py:378 -- client gRPC channel state change: ChannelConnectivity.IDLE\n",
- "2023-05-31 14:12:38,034\tDEBUG worker.py:378 -- client gRPC channel state change: ChannelConnectivity.CONNECTING\n",
- "2023-05-31 14:12:38,246\tDEBUG worker.py:378 -- client gRPC channel state change: ChannelConnectivity.READY\n",
- "2023-05-31 14:12:38,290\tDEBUG worker.py:807 -- Pinging server.\n",
- "2023-05-31 14:12:40,521\tDEBUG worker.py:640 -- Retaining 00ffffffffffffffffffffffffffffffffffffff0100000001000000\n",
- "2023-05-31 14:12:40,523\tDEBUG worker.py:564 -- Scheduling task get_dashboard_url 0 b'\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00'\n",
- "2023-05-31 14:12:40,535\tDEBUG worker.py:640 -- Retaining c8ef45ccd0112571ffffffffffffffffffffffff0100000001000000\n",
- "2023-05-31 14:12:41,379\tDEBUG worker.py:636 -- Releasing c8ef45ccd0112571ffffffffffffffffffffffff0100000001000000\n"
+ "2023-06-27 19:14:16,088\tINFO client_builder.py:251 -- Passing the following kwargs to ray.init() on the server: logging_level\n",
+ "2023-06-27 19:14:16,100\tDEBUG worker.py:378 -- client gRPC channel state change: ChannelConnectivity.IDLE\n",
+ "2023-06-27 19:14:16,308\tDEBUG worker.py:378 -- client gRPC channel state change: ChannelConnectivity.CONNECTING\n",
+ "2023-06-27 19:14:16,434\tDEBUG worker.py:378 -- client gRPC channel state change: ChannelConnectivity.READY\n",
+ "2023-06-27 19:14:16,436\tDEBUG worker.py:807 -- Pinging server.\n",
+ "2023-06-27 19:14:18,634\tDEBUG worker.py:640 -- Retaining 00ffffffffffffffffffffffffffffffffffffff0100000001000000\n",
+ "2023-06-27 19:14:18,635\tDEBUG worker.py:564 -- Scheduling task get_dashboard_url 0 b'\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00'\n",
+ "2023-06-27 19:14:18,645\tDEBUG worker.py:640 -- Retaining c8ef45ccd0112571ffffffffffffffffffffffff0100000001000000\n",
+ "2023-06-27 19:14:19,454\tDEBUG worker.py:636 -- Releasing c8ef45ccd0112571ffffffffffffffffffffffff0100000001000000\n"
]
},
{
@@ -190,7 +164,7 @@
" \n",
"
\n",
" Dashboard: | \n",
- " http://10.254.12.141:8265 | \n",
+ " http://10.254.20.41:8265 | \n",
"
\n",
"\n",
" \n",
@@ -198,10 +172,10 @@
"\n"
],
"text/plain": [
- "ClientContext(dashboard_url='10.254.12.141:8265', python_version='3.8.13', ray_version='2.1.0', ray_commit='23f34d948dae8de9b168667ab27e6cf940b3ae85', protocol_version='2022-10-05', _num_clients=1, _context_to_restore=)"
+ "ClientContext(dashboard_url='10.254.20.41:8265', python_version='3.8.13', ray_version='2.1.0', ray_commit='23f34d948dae8de9b168667ab27e6cf940b3ae85', protocol_version='2022-10-05', _num_clients=1, _context_to_restore=)"
]
},
- "execution_count": 12,
+ "execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
@@ -210,12 +184,12 @@
"import ray\n",
"\n",
"ray.shutdown()\n",
- "ray.init(address=f\"ray://{rayclient_url}\", logging_level=\"DEBUG\")"
+ "ray.init(address=cluster.local_client_url(), logging_level=\"DEBUG\")"
]
},
{
"cell_type": "code",
- "execution_count": 13,
+ "execution_count": 7,
"id": "3436eb4a-217c-4109-a3c3-309fda7e2442",
"metadata": {},
"outputs": [],
@@ -239,7 +213,7 @@
},
{
"cell_type": "code",
- "execution_count": 14,
+ "execution_count": 8,
"id": "5cca1874-2be3-4631-ae48-9adfa45e3af3",
"metadata": {
"scrolled": true,
@@ -250,8 +224,8 @@
"name": "stderr",
"output_type": "stream",
"text": [
- "2023-05-31 14:13:29,868\tDEBUG worker.py:640 -- Retaining 00ffffffffffffffffffffffffffffffffffffff0100000002000000\n",
- "2023-05-31 14:13:29,870\tDEBUG worker.py:564 -- Scheduling task heavy_calculation 0 b'\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00'\n"
+ "2023-06-27 19:14:28,222\tDEBUG worker.py:640 -- Retaining 00ffffffffffffffffffffffffffffffffffffff0100000002000000\n",
+ "2023-06-27 19:14:28,222\tDEBUG worker.py:564 -- Scheduling task heavy_calculation 0 b'\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00'\n"
]
}
],
@@ -261,7 +235,7 @@
},
{
"cell_type": "code",
- "execution_count": 15,
+ "execution_count": 9,
"id": "01172c29-e8bf-41ef-8db5-eccb07906111",
"metadata": {},
"outputs": [
@@ -269,8 +243,8 @@
"name": "stderr",
"output_type": "stream",
"text": [
- "2023-05-31 14:13:32,643\tDEBUG worker.py:640 -- Retaining 16310a0f0a45af5cffffffffffffffffffffffff0100000001000000\n",
- "2023-05-31 14:13:34,677\tDEBUG worker.py:439 -- Internal retry for get [ClientObjectRef(16310a0f0a45af5cffffffffffffffffffffffff0100000001000000)]\n"
+ "2023-06-27 19:14:29,202\tDEBUG worker.py:640 -- Retaining 16310a0f0a45af5cffffffffffffffffffffffff0100000001000000\n",
+ "2023-06-27 19:14:31,224\tDEBUG worker.py:439 -- Internal retry for get [ClientObjectRef(16310a0f0a45af5cffffffffffffffffffffffff0100000001000000)]\n"
]
},
{
@@ -279,7 +253,7 @@
"1789.4644387076714"
]
},
- "execution_count": 15,
+ "execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
@@ -290,7 +264,7 @@
},
{
"cell_type": "code",
- "execution_count": 16,
+ "execution_count": 10,
"id": "9e79b547-a457-4232-b77d-19147067b972",
"metadata": {},
"outputs": [
@@ -298,10 +272,10 @@
"name": "stderr",
"output_type": "stream",
"text": [
- "2023-05-31 14:13:37,659\tDEBUG dataclient.py:287 -- Got unawaited response connection_cleanup {\n",
+ "2023-06-27 19:14:33,161\tDEBUG dataclient.py:287 -- Got unawaited response connection_cleanup {\n",
"}\n",
"\n",
- "2023-05-31 14:13:38,681\tDEBUG dataclient.py:278 -- Shutting down data channel.\n"
+ "2023-06-27 19:14:34,460\tDEBUG dataclient.py:278 -- Shutting down data channel.\n"
]
}
],
@@ -312,7 +286,7 @@
},
{
"cell_type": "code",
- "execution_count": 17,
+ "execution_count": 11,
"id": "2c198f1f-68bf-43ff-a148-02b5cb000ff2",
"metadata": {},
"outputs": [],
diff --git a/docs/cluster/auth.html b/docs/cluster/auth.html
index 15b563f9..dbec66ac 100644
--- a/docs/cluster/auth.html
+++ b/docs/cluster/auth.html
@@ -53,8 +53,12 @@ Module codeflare_sdk.cluster.auth
"""
import abc
-import openshift as oc
-from openshift import OpenShiftPythonException
+from kubernetes import client, config
+
+global api_client
+api_client = None
+global config_path
+config_path = None
class Authentication(metaclass=abc.ABCMeta):
@@ -76,83 +80,134 @@ Module codeflare_sdk.cluster.auth
pass
+class KubeConfiguration(metaclass=abc.ABCMeta):
+ """
+ An abstract class that defines the method for loading a user defined config file using the `load_kube_config()` function
+ """
+
+ def load_kube_config(self):
+ """
+ Method for setting your Kubernetes configuration to a certain file
+ """
+ pass
+
+ def logout(self):
+ """
+ Method for logging out of the remote cluster
+ """
+ pass
+
+
class TokenAuthentication(Authentication):
"""
- `TokenAuthentication` is a subclass of `Authentication`. It can be used to authenticate to an OpenShift
+ `TokenAuthentication` is a subclass of `Authentication`. It can be used to authenticate to a Kubernetes
cluster when the user has an API token and the API server address.
"""
- def __init__(self, token: str = None, server: str = None, skip_tls: bool = False):
+ def __init__(
+ self,
+ token: str,
+ server: str,
+ skip_tls: bool = False,
+ ca_cert_path: str = None,
+ ):
"""
Initialize a TokenAuthentication object that requires a value for `token`, the API Token
- and `server`, the API server address for authenticating to an OpenShift cluster.
+ and `server`, the API server address for authenticating to a Kubernetes cluster.
"""
self.token = token
self.server = server
self.skip_tls = skip_tls
+ self.ca_cert_path = ca_cert_path
def login(self) -> str:
"""
- This function is used to login to an OpenShift cluster using the user's API token and API server address.
- Depending on the cluster, a user can choose to login in with "--insecure-skip-tls-verify` by setting `skip_tls`
- to `True`.
+ This function is used to log in to a Kubernetes cluster using the user's API token and API server address.
+ Depending on the cluster, a user can choose to login in with `--insecure-skip-tls-verify` by setting `skip_tls`
+ to `True` or `--certificate-authority` by setting `skip_tls` to False and providing a path to a ca bundle with `ca_cert_path`.
"""
- args = [f"--token={self.token}", f"--server={self.server}"]
- if self.skip_tls:
- args.append("--insecure-skip-tls-verify")
+ global config_path
+ global api_client
try:
- response = oc.invoke("login", args)
- except OpenShiftPythonException as osp: # pragma: no cover
- error_msg = osp.result.err()
- if "The server uses a certificate signed by unknown authority" in error_msg:
- return "Error: certificate auth failure, please set `skip_tls=True` in TokenAuthentication"
- elif "invalid" in error_msg:
- raise PermissionError(error_msg)
+ configuration = client.Configuration()
+ configuration.api_key_prefix["authorization"] = "Bearer"
+ configuration.host = self.server
+ configuration.api_key["authorization"] = self.token
+ if self.skip_tls == False and self.ca_cert_path == None:
+ configuration.verify_ssl = True
+ elif self.skip_tls == False:
+ configuration.ssl_ca_cert = self.ca_cert_path
else:
- return error_msg
- return response.out()
+ configuration.verify_ssl = False
+ api_client = client.ApiClient(configuration)
+ client.AuthenticationApi(api_client).get_api_group()
+ config_path = None
+ return "Logged into %s" % self.server
+ except client.ApiException: # pragma: no cover
+ api_client = None
+ print("Authentication Error please provide the correct token + server")
def logout(self) -> str:
"""
- This function is used to logout of an OpenShift cluster.
+ This function is used to logout of a Kubernetes cluster.
"""
- args = [f"--token={self.token}", f"--server={self.server}"]
- response = oc.invoke("logout", args)
- return response.out()
+ global config_path
+ config_path = None
+ global api_client
+ api_client = None
+ return "Successfully logged out of %s" % self.server
-class PasswordUserAuthentication(Authentication):
+class KubeConfigFileAuthentication(KubeConfiguration):
"""
- `PasswordUserAuthentication` is a subclass of `Authentication`. It can be used to authenticate to an OpenShift
- cluster when the user has a username and password.
+ A class that defines the necessary methods for passing a user's own Kubernetes config file.
+ Specifically this class defines the `load_kube_config()` and `config_check()` functions.
"""
- def __init__(
- self,
- username: str = None,
- password: str = None,
- ):
- """
- Initialize a PasswordUserAuthentication object that requires a value for `username`
- and `password` for authenticating to an OpenShift cluster.
- """
- self.username = username
- self.password = password
+ def __init__(self, kube_config_path: str = None):
+ self.kube_config_path = kube_config_path
- def login(self) -> str:
+ def load_kube_config(self):
"""
- This function is used to login to an OpenShift cluster using the user's `username` and `password`.
+ Function for loading a user's own predefined Kubernetes config file.
"""
- response = oc.login(self.username, self.password)
- return response.out()
+ global config_path
+ global api_client
+ try:
+ if self.kube_config_path == None:
+ return "Please specify a config file path"
+ config_path = self.kube_config_path
+ api_client = None
+ config.load_kube_config(config_path)
+ response = "Loaded user config file at path %s" % self.kube_config_path
+ except config.ConfigException: # pragma: no cover
+ config_path = None
+ raise Exception("Please specify a config file path")
+ return response
- def logout(self) -> str:
- """
- This function is used to logout of an OpenShift cluster.
- """
- response = oc.invoke("logout")
- return response.out()
+
+def config_check() -> str:
+ """
+ Function for loading the config file at the default config location ~/.kube/config if the user has not
+ specified their own config file or has logged in with their token and server.
+ """
+ global config_path
+ global api_client
+ if config_path == None and api_client == None:
+ config.load_kube_config()
+ if config_path != None and api_client == None:
+ return config_path
+
+
+def api_config_handler() -> str:
+ """
+ This function is used to load the api client if the user has logged in
+ """
+ if api_client != None and config_path == None:
+ return api_client
+ else:
+ return None
@@ -160,6 +215,51 @@ Module codeflare_sdk.cluster.auth
+
+
+
+def api_config_handler() ‑> str
+
+-
+
This function is used to load the api client if the user has logged in
+
+
+Expand source code
+
+def api_config_handler() -> str:
+ """
+ This function is used to load the api client if the user has logged in
+ """
+ if api_client != None and config_path == None:
+ return api_client
+ else:
+ return None
+
+
+
+def config_check() ‑> str
+
+-
+
Function for loading the config file at the default config location ~/.kube/config if the user has not
+specified their own config file or has logged in with their token and server.
+
+
+Expand source code
+
+def config_check() -> str:
+ """
+ Function for loading the config file at the default config location ~/.kube/config if the user has not
+ specified their own config file or has logged in with their token and server.
+ """
+ global config_path
+ global api_client
+ if config_path == None and api_client == None:
+ config.load_kube_config()
+ if config_path != None and api_client == None:
+ return config_path
+
+
+
@@ -194,7 +294,6 @@
Subclasses
Methods
@@ -233,150 +332,226 @@ Methods
-
-class PasswordUserAuthentication
-(username: str = None, password: str = None)
+
+class KubeConfigFileAuthentication
+(kube_config_path: str = None)
-PasswordUserAuthentication
is a subclass of Authentication
. It can be used to authenticate to an OpenShift
-cluster when the user has a username and password.
-
Initialize a PasswordUserAuthentication object that requires a value for username
-and password
for authenticating to an OpenShift cluster.
+A class that defines the necessary methods for passing a user's own Kubernetes config file.
+Specifically this class defines the load_kube_config()
and config_check()
functions.
Expand source code
-class PasswordUserAuthentication(Authentication):
+class KubeConfigFileAuthentication(KubeConfiguration):
"""
- `PasswordUserAuthentication` is a subclass of `Authentication`. It can be used to authenticate to an OpenShift
- cluster when the user has a username and password.
+ A class that defines the necessary methods for passing a user's own Kubernetes config file.
+ Specifically this class defines the `load_kube_config()` and `config_check()` functions.
"""
- def __init__(
- self,
- username: str = None,
- password: str = None,
- ):
+ def __init__(self, kube_config_path: str = None):
+ self.kube_config_path = kube_config_path
+
+ def load_kube_config(self):
"""
- Initialize a PasswordUserAuthentication object that requires a value for `username`
- and `password` for authenticating to an OpenShift cluster.
+ Function for loading a user's own predefined Kubernetes config file.
"""
- self.username = username
- self.password = password
+ global config_path
+ global api_client
+ try:
+ if self.kube_config_path == None:
+ return "Please specify a config file path"
+ config_path = self.kube_config_path
+ api_client = None
+ config.load_kube_config(config_path)
+ response = "Loaded user config file at path %s" % self.kube_config_path
+ except config.ConfigException: # pragma: no cover
+ config_path = None
+ raise Exception("Please specify a config file path")
+ return response
+
+Ancestors
+
+Methods
+
+
+def load_kube_config(self)
+
+-
+
Function for loading a user's own predefined Kubernetes config file.
+
+
+Expand source code
+
+def load_kube_config(self):
+ """
+ Function for loading a user's own predefined Kubernetes config file.
+ """
+ global config_path
+ global api_client
+ try:
+ if self.kube_config_path == None:
+ return "Please specify a config file path"
+ config_path = self.kube_config_path
+ api_client = None
+ config.load_kube_config(config_path)
+ response = "Loaded user config file at path %s" % self.kube_config_path
+ except config.ConfigException: # pragma: no cover
+ config_path = None
+ raise Exception("Please specify a config file path")
+ return response
+
+
+
+Inherited members
+
+
+
+class KubeConfiguration
+
+
+An abstract class that defines the method for loading a user defined config file using the load_kube_config()
function
+
+
+Expand source code
+
+class KubeConfiguration(metaclass=abc.ABCMeta):
+ """
+ An abstract class that defines the method for loading a user defined config file using the `load_kube_config()` function
+ """
- def login(self) -> str:
+ def load_kube_config(self):
"""
- This function is used to login to an OpenShift cluster using the user's `username` and `password`.
+ Method for setting your Kubernetes configuration to a certain file
"""
- response = oc.login(self.username, self.password)
- return response.out()
+ pass
- def logout(self) -> str:
+ def logout(self):
"""
- This function is used to logout of an OpenShift cluster.
+ Method for logging out of the remote cluster
"""
- response = oc.invoke("logout")
- return response.out()
+ pass
-Ancestors
+Subclasses
Methods
-
-def login(self) ‑> str
+
+def load_kube_config(self)
-
-
This function is used to login to an OpenShift cluster using the user's username
and password
.
+Method for setting your Kubernetes configuration to a certain file
Expand source code
-def login(self) -> str:
+def load_kube_config(self):
"""
- This function is used to login to an OpenShift cluster using the user's `username` and `password`.
+ Method for setting your Kubernetes configuration to a certain file
"""
- response = oc.login(self.username, self.password)
- return response.out()
+ pass
-
-def logout(self) ‑> str
+
+def logout(self)
-
-
This function is used to logout of an OpenShift cluster.
+Method for logging out of the remote cluster
Expand source code
-def logout(self) -> str:
+def logout(self):
"""
- This function is used to logout of an OpenShift cluster.
+ Method for logging out of the remote cluster
"""
- response = oc.invoke("logout")
- return response.out()
+ pass
class TokenAuthentication
-(token: str = None, server: str = None, skip_tls: bool = False)
+(token: str, server: str, skip_tls: bool = False, ca_cert_path: str = None)
-TokenAuthentication
is a subclass of Authentication
. It can be used to authenticate to an OpenShift
+
TokenAuthentication
is a subclass of Authentication
. It can be used to authenticate to a Kubernetes
cluster when the user has an API token and the API server address.
Initialize a TokenAuthentication object that requires a value for token
, the API Token
-and server
, the API server address for authenticating to an OpenShift cluster.
+and
server
, the API server address for authenticating to a Kubernetes cluster.
Expand source code
class TokenAuthentication(Authentication):
"""
- `TokenAuthentication` is a subclass of `Authentication`. It can be used to authenticate to an OpenShift
+ `TokenAuthentication` is a subclass of `Authentication`. It can be used to authenticate to a Kubernetes
cluster when the user has an API token and the API server address.
"""
- def __init__(self, token: str = None, server: str = None, skip_tls: bool = False):
+ def __init__(
+ self,
+ token: str,
+ server: str,
+ skip_tls: bool = False,
+ ca_cert_path: str = None,
+ ):
"""
Initialize a TokenAuthentication object that requires a value for `token`, the API Token
- and `server`, the API server address for authenticating to an OpenShift cluster.
+ and `server`, the API server address for authenticating to a Kubernetes cluster.
"""
self.token = token
self.server = server
self.skip_tls = skip_tls
+ self.ca_cert_path = ca_cert_path
def login(self) -> str:
"""
- This function is used to login to an OpenShift cluster using the user's API token and API server address.
- Depending on the cluster, a user can choose to login in with "--insecure-skip-tls-verify` by setting `skip_tls`
- to `True`.
+ This function is used to log in to a Kubernetes cluster using the user's API token and API server address.
+ Depending on the cluster, a user can choose to login in with `--insecure-skip-tls-verify` by setting `skip_tls`
+ to `True` or `--certificate-authority` by setting `skip_tls` to False and providing a path to a ca bundle with `ca_cert_path`.
"""
- args = [f"--token={self.token}", f"--server={self.server}"]
- if self.skip_tls:
- args.append("--insecure-skip-tls-verify")
+ global config_path
+ global api_client
try:
- response = oc.invoke("login", args)
- except OpenShiftPythonException as osp: # pragma: no cover
- error_msg = osp.result.err()
- if "The server uses a certificate signed by unknown authority" in error_msg:
- return "Error: certificate auth failure, please set `skip_tls=True` in TokenAuthentication"
- elif "invalid" in error_msg:
- raise PermissionError(error_msg)
+ configuration = client.Configuration()
+ configuration.api_key_prefix["authorization"] = "Bearer"
+ configuration.host = self.server
+ configuration.api_key["authorization"] = self.token
+ if self.skip_tls == False and self.ca_cert_path == None:
+ configuration.verify_ssl = True
+ elif self.skip_tls == False:
+ configuration.ssl_ca_cert = self.ca_cert_path
else:
- return error_msg
- return response.out()
+ configuration.verify_ssl = False
+ api_client = client.ApiClient(configuration)
+ client.AuthenticationApi(api_client).get_api_group()
+ config_path = None
+ return "Logged into %s" % self.server
+ except client.ApiException: # pragma: no cover
+ api_client = None
+ print("Authentication Error please provide the correct token + server")
def logout(self) -> str:
"""
- This function is used to logout of an OpenShift cluster.
+ This function is used to logout of a Kubernetes cluster.
"""
- args = [f"--token={self.token}", f"--server={self.server}"]
- response = oc.invoke("logout", args)
- return response.out()
+ global config_path
+ config_path = None
+ global api_client
+ api_client = None
+ return "Successfully logged out of %s" % self.server
Ancestors
@@ -388,51 +563,59 @@ Methods
def login(self) ‑> str
-
-
This function is used to login to an OpenShift cluster using the user's API token and API server address.
-Depending on the cluster, a user can choose to login in with "–insecure-skip-tls-verify by setting
skip_tls`
-to True
.
+This function is used to log in to a Kubernetes cluster using the user's API token and API server address.
+Depending on the cluster, a user can choose to login in with --insecure-skip-tls-verify
by setting skip_tls
+to True
or --certificate-authority
by setting skip_tls
to False and providing a path to a ca bundle with ca_cert_path
.
Expand source code
def login(self) -> str:
"""
- This function is used to login to an OpenShift cluster using the user's API token and API server address.
- Depending on the cluster, a user can choose to login in with "--insecure-skip-tls-verify` by setting `skip_tls`
- to `True`.
+ This function is used to log in to a Kubernetes cluster using the user's API token and API server address.
+ Depending on the cluster, a user can choose to login in with `--insecure-skip-tls-verify` by setting `skip_tls`
+ to `True` or `--certificate-authority` by setting `skip_tls` to False and providing a path to a ca bundle with `ca_cert_path`.
"""
- args = [f"--token={self.token}", f"--server={self.server}"]
- if self.skip_tls:
- args.append("--insecure-skip-tls-verify")
+ global config_path
+ global api_client
try:
- response = oc.invoke("login", args)
- except OpenShiftPythonException as osp: # pragma: no cover
- error_msg = osp.result.err()
- if "The server uses a certificate signed by unknown authority" in error_msg:
- return "Error: certificate auth failure, please set `skip_tls=True` in TokenAuthentication"
- elif "invalid" in error_msg:
- raise PermissionError(error_msg)
+ configuration = client.Configuration()
+ configuration.api_key_prefix["authorization"] = "Bearer"
+ configuration.host = self.server
+ configuration.api_key["authorization"] = self.token
+ if self.skip_tls == False and self.ca_cert_path == None:
+ configuration.verify_ssl = True
+ elif self.skip_tls == False:
+ configuration.ssl_ca_cert = self.ca_cert_path
else:
- return error_msg
- return response.out()
+ configuration.verify_ssl = False
+ api_client = client.ApiClient(configuration)
+ client.AuthenticationApi(api_client).get_api_group()
+ config_path = None
+ return "Logged into %s" % self.server
+ except client.ApiException: # pragma: no cover
+ api_client = None
+ print("Authentication Error please provide the correct token + server")
def logout(self) ‑> str
-
-
This function is used to logout of an OpenShift cluster.
+This function is used to logout of a Kubernetes cluster.
Expand source code
def logout(self) -> str:
"""
- This function is used to logout of an OpenShift cluster.
+ This function is used to logout of a Kubernetes cluster.
"""
- args = [f"--token={self.token}", f"--server={self.server}"]
- response = oc.invoke("logout", args)
- return response.out()
+ global config_path
+ config_path = None
+ global api_client
+ api_client = None
+ return "Successfully logged out of %s" % self.server
@@ -451,6 +634,12 @@ Index
codeflare_sdk.cluster
+
+
+
-
@@ -461,10 +650,16 @@
+
+
+
+-
+
-
@@ -483,4 +678,4 @@