|
| 1 | +from typing import Any, Dict, List, Tuple, Union |
| 2 | +from truefoundry.workflow import ( |
| 3 | + task, |
| 4 | + workflow, |
| 5 | + PythonTaskConfig, |
| 6 | + TaskPythonBuild, |
| 7 | + map_task, |
| 8 | + conditional, |
| 9 | +) |
| 10 | +from truefoundry.deploy import Resources |
| 11 | +from functools import partial |
| 12 | +import tensorflow as tf |
| 13 | +from tensorflow.keras.datasets import mnist |
| 14 | +import numpy as np |
| 15 | + |
| 16 | + |
| 17 | +task_config = PythonTaskConfig( |
| 18 | + image=TaskPythonBuild( |
| 19 | + python_version="3.9", |
| 20 | + pip_packages=[ |
| 21 | + "truefoundry[workflow]==0.5.2", |
| 22 | + "tensorflow==2.15.0", |
| 23 | + "s3fs>=2024.10.0", |
| 24 | + ], |
| 25 | + ), |
| 26 | + resources=Resources( |
| 27 | + cpu_request=1.2, |
| 28 | + cpu_limit=1.2, |
| 29 | + memory_limit=3000, |
| 30 | + memory_request=3000, |
| 31 | + ephemeral_storage_limit=2000, |
| 32 | + ephemeral_storage_request=2000, |
| 33 | + ), |
| 34 | + service_account="default", |
| 35 | + env={ |
| 36 | + "TF_CPP_MIN_LOG_LEVEL": "3", # suppress tensorflow warnings |
| 37 | + "FLYTE_SDK_LOGGING_LEVEL": "40", |
| 38 | + "TFY_API_KEY": "<your-api-key>", |
| 39 | + "TFY_HOST": "<tfy-host-value>", |
| 40 | + }, |
| 41 | +) |
| 42 | + |
| 43 | + |
| 44 | +@task(task_config=task_config) |
| 45 | +def fetch_data() -> Dict[str, np.array]: |
| 46 | + (x_train, y_train), (x_test, y_test) = mnist.load_data() |
| 47 | + return {"x_train": x_train, "y_train": y_train, "x_test": x_test, "y_test": y_test} |
| 48 | + |
| 49 | + |
| 50 | +@task(task_config=task_config) |
| 51 | +def train_model( |
| 52 | + epochs: int, learning_rate: float, data: Dict[str, np.array], ml_repo: str |
| 53 | +) -> str: |
| 54 | + from truefoundry.ml import get_client |
| 55 | + |
| 56 | + x_train, y_train, x_test, y_test = ( |
| 57 | + data["x_train"], |
| 58 | + data["y_train"], |
| 59 | + data["x_test"], |
| 60 | + data["y_test"], |
| 61 | + ) |
| 62 | + x_train = x_train / 255.0 |
| 63 | + x_test = x_test / 255.0 |
| 64 | + |
| 65 | + client = get_client() |
| 66 | + run = client.create_run(ml_repo=ml_repo) |
| 67 | + |
| 68 | + model = tf.keras.Sequential( |
| 69 | + [ |
| 70 | + tf.keras.layers.Flatten(), |
| 71 | + tf.keras.layers.Dense(128, activation="relu"), |
| 72 | + tf.keras.layers.Dense(10, activation="softmax"), |
| 73 | + ] |
| 74 | + ) |
| 75 | + |
| 76 | + optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate) |
| 77 | + # Compile the model |
| 78 | + model.compile( |
| 79 | + optimizer=optimizer, |
| 80 | + loss="sparse_categorical_crossentropy", |
| 81 | + metrics=["accuracy"], |
| 82 | + ) |
| 83 | + |
| 84 | + epochs = epochs |
| 85 | + print(f"Started training the model for {epochs} epochs") |
| 86 | + history = model.fit( |
| 87 | + x_train, y_train, epochs=epochs, validation_data=(x_test, y_test) |
| 88 | + ) |
| 89 | + |
| 90 | + # Evaluate the model |
| 91 | + loss, accuracy = model.evaluate(x_test, y_test) |
| 92 | + print(f"Test loss: {loss}") |
| 93 | + print(f"Test accuracy: {accuracy}") |
| 94 | + |
| 95 | + history_dict = history.history |
| 96 | + train_accuracy = history_dict["accuracy"] |
| 97 | + val_accuracy = history_dict["val_accuracy"] |
| 98 | + loss = history_dict["loss"] |
| 99 | + |
| 100 | + for epoch in range(epochs): |
| 101 | + run.log_metrics( |
| 102 | + { |
| 103 | + "train_accuracy": train_accuracy[epoch], |
| 104 | + "val_accuracy": val_accuracy[epoch], |
| 105 | + "loss": loss[epoch], |
| 106 | + }, |
| 107 | + step=epoch + 5, |
| 108 | + ) |
| 109 | + |
| 110 | + model.save("mnist_model.h5") |
| 111 | + |
| 112 | + run.log_model( |
| 113 | + name="handwritten-digits-recognition", |
| 114 | + model_file_or_folder="mnist_model.h5", |
| 115 | + framework="tensorflow", |
| 116 | + description="sample model to recognize the handwritten digits", |
| 117 | + metadata={"accuracy": accuracy, "loss": loss}, |
| 118 | + step=1, |
| 119 | + ) |
| 120 | + |
| 121 | + run_fqn = run.fqn |
| 122 | + run.end() |
| 123 | + return run_fqn |
| 124 | + |
| 125 | + |
| 126 | +@task(task_config=task_config) |
| 127 | +def get_best_model(fqns: List[str], threshold: float) -> Tuple[str, bool]: |
| 128 | + from truefoundry.ml import get_client |
| 129 | + |
| 130 | + client = get_client() |
| 131 | + curr_accuracy = 0 |
| 132 | + best_fqn = None |
| 133 | + print(f"Finding the best models from {len(fqns)} models") |
| 134 | + for fqn_no in range(len(fqns)): |
| 135 | + print(f"Comparing accuracy for model {fqn_no+1}") |
| 136 | + run = client.get_run_by_fqn(fqns[fqn_no]) |
| 137 | + accuracy_metric = run.get_metrics().get("val_accuracy", 0) |
| 138 | + accuracy = accuracy_metric[-1].value |
| 139 | + if accuracy > curr_accuracy and accuracy > threshold: |
| 140 | + curr_accuracy = accuracy |
| 141 | + best_fqn = fqns[fqn_no] |
| 142 | + if best_fqn: |
| 143 | + print("The fqn of the best model is: ", best_fqn) |
| 144 | + return best_fqn, True |
| 145 | + print("No model found with accuracy greater than threshold") |
| 146 | + return "", False |
| 147 | + |
| 148 | + |
| 149 | +@task(task_config=task_config) |
| 150 | +def deploy_model(run_fqn: str, workspace_fqn: str) -> str: |
| 151 | + from truefoundry.ml import get_client |
| 152 | + from deploy_model.deploy import deploy_service |
| 153 | + |
| 154 | + client = get_client() |
| 155 | + run = client.get_run_by_fqn(run_fqn) |
| 156 | + models = run.list_model_versions() |
| 157 | + model = models.__next__() |
| 158 | + print(f"Deploying model {model.fqn}") |
| 159 | + url = deploy_service(model_version_fqn=model.fqn, workspace_fqn=workspace_fqn) |
| 160 | + return f"Model deployed at {url}" |
| 161 | + |
| 162 | + |
| 163 | +@task(task_config=task_config) |
| 164 | +def do_nothing(threshold: float) -> str: |
| 165 | + return f"Model with threshold greater than {threshold} not found" |
| 166 | + |
| 167 | + |
| 168 | +@workflow |
| 169 | +def model_training_workflow( |
| 170 | + ml_repo: str, |
| 171 | + workspace_fqn: str, |
| 172 | + epochs: List[int] = [2, 3, 5], |
| 173 | + learning_rate: List[float] = [0.1, 0.001, 0.001], |
| 174 | + accuracy_threshold: float = 0.15, |
| 175 | +) -> Union[str, None]: |
| 176 | + data = fetch_data() |
| 177 | + train_model_function = partial(train_model, data=data, ml_repo=ml_repo) |
| 178 | + fqns = map_task(train_model_function, concurrency=2)( |
| 179 | + epochs=epochs, learning_rate=learning_rate |
| 180 | + ) |
| 181 | + model_version_fqn, does_model_pass_threshold_accuracy = get_best_model( |
| 182 | + fqns=fqns, threshold=accuracy_threshold |
| 183 | + ) |
| 184 | + message = ( |
| 185 | + conditional("Deploy model") |
| 186 | + .if_(does_model_pass_threshold_accuracy == True) |
| 187 | + .then(deploy_model(run_fqn=model_version_fqn, workspace_fqn=workspace_fqn)) |
| 188 | + .else_() |
| 189 | + .then(do_nothing(threshold=accuracy_threshold)) |
| 190 | + ) |
| 191 | + |
| 192 | + return message |
0 commit comments